Why is -lm not needed in some cases when compiling and linking C code?

I have an example file:

#include <stdio.h> #include <math.h> int main(){ printf("%f\n", log(10)); } 

When I compile it with gcc sample.c -oa , it works fine. I can run it with ./a and it gives output 2.302585 as expected.

However, when my file looks like this:

 #include <stdio.h> #include <math.h> int main(){ double a = 10; printf("%f\n", log(a)); } 

it does not compile with gcc sample.c -oa . Instead, I should use gcc sample.c -oa -lm so that I can apparently say “link math” ... What I really don't understand, why don't I link the math in the first example? And what exactly does this mean even to “connect mathematics”? It's been a while since I worked with C compilers, so forgive me if this is a bad question.

+8
c compiler-optimization gcc macros
source share
3 answers

Check the disassembly, and you will most likely find that the compiler fully optimizes the call to log() completely in the first case (so that nothing is referenced), but not in the second. In this particular case, glibc defines:

 # define M_LN10 2.30258509299404568402 

in math.h , for example, any standard library function can be implemented as a macro, so it can calculate some of these things without calling the function.

+6
source share

The functions of the math library cannot be called, according to the GCC document , some built-in functions are defined and can be called instead in certain circumstances.

... The GNU C library provides optimizations for many commonly used math functions. When GNU CC is used and the user activates the optimizer, several new built-in functions and macros are defined. These new functions and macros have the same names as the library functions, and therefore are used instead of the latter. In the case of built-in functions, the compiler will decide if it is wise to use them, and this solution is usually the right one.

This means that there is no need to access library functions and can significantly increase the speed of the generated code. The disadvantage is that the code size will increase, and the increase is not always negligible.

+5
source share

For some reason, gcc optimizes log (const) even with -O0. Therefore, in the first case, the call to log () is absent. Check assembly to check:

gcc sample.c -S

clang, for example, does not optimize it on O0. But in O2, gcc optimizes the call in both cases.

+2
source share

All Articles