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

前端 未结 3 570
广开言路
广开言路 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 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.

提交回复
热议问题