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

前端 未结 3 569
广开言路
广开言路 2020-12-17 22:32

I have a sample file here:

#include 
#include 

int main(){
  printf(\"%f\\n\", log(10));
}

When I compile it

相关标签:
3条回答
  • 2020-12-17 22:47

    The math library functions may not be called, according to GCC document, some inline functions are defined and may be called instead in certain circumstances.

    ... The GNU C Library provides optimizations for many of the frequently-used math functions. When GNU CC is used and the user activates the optimizer, several new inline functions and macros are defined. These new functions and macros have the same names as the library functions and so are used instead of the latter. In the case of inline functions the compiler will decide whether it is reasonable to use them, and this decision is usually correct.

    This means that no calls to the library functions may be necessary, and can increase the speed of generated code significantly. The drawback is that code size will increase, and the increase is not always negligible.

    0 讨论(0)
  • 2020-12-17 23:01

    Check the disassembly, and you'll likely find that the compiler is optimizing the call to log() out entirely in the first case (so there's nothing to link), but not in the second. In this particular case, glibc defines:

    # define M_LN10     2.30258509299404568402
    

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

    0 讨论(0)
  • 2020-12-17 23:04

    For some reasons gcc optimizes log(const) even with -O0. So there's no log() call in the first case. Check assembly to verify:

    gcc sample.c -S

    clang, for example doesn't optimize it out on O0. But at O2 gcc optimizes the call in both cases.

    0 讨论(0)
提交回复
热议问题