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

不打扰是莪最后的温柔 提交于 2019-11-29 06:42:10

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!