Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C libm.a not needed to be linked when compiling

Tags:

c

gcc

I was trying to compile a source file that includes <math.h>. However I succeeded in creating an executable, no error without linking to libm.a.

The command I typed was gcc -Wall filename.c -o executablename

I was told to link to the external libraries (i.e/ libraries other than libc.a)

What's going on?

#include <math.h>
#include <stdio.h>

int main(void)
{
    double x = sqrt(2.0);
    printf ("The sqrt of 2 is: %f\n", x);
    return 0;
}
like image 303
Daniel Jee Avatar asked Mar 08 '26 11:03

Daniel Jee


2 Answers

The math functions you call are implemented by compiler built-in functions. Try the following if you want to see an error message:

gcc -fno-builtin -Wall filename.c -o executablename

For example, on my platform (Ubuntu 14.04.3 LTS), I get this error message:

$ cat x.c
#include <math.h>
#include <stdio.h>

int main(void)
{
    double x = sqrt(2.0);
    printf ("The sqrt of 2 is: %f\n", x);
    return 0;
}
$ gcc -fno-builtin x.c
/tmp/ccpjG2Pb.o: In function `main':
x.c:(.text+0x1c): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status
like image 108
Robᵩ Avatar answered Mar 11 '26 02:03

Robᵩ


The functions in <math.h> (or the preferable <tgmath.h>) are part of the C library just as many other functions. It is platform dependent if all the functions in the C library are actually linked in one single library or separately in multiple chunks.

In ancient times the size of the libraries was a problem for link time, the larger a library was, the longer it took to link executables that had many unresolved symbols. These times are long gone, but the separation on some platforms into libc.a and libm.a prevails.

If your platform doesn't need -lm for linking it should have a dummy (empty) version of libm.a just that there is no error when you have that on your link command line. This is for example the case for the musl C library that is at the base of Alpine Linux.

like image 23
Jens Gustedt Avatar answered Mar 11 '26 02:03

Jens Gustedt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!