Error when using math function in gcc?

When I pass a constant value to log2 (), following

#include <stdio.h> #include<math.h> int main(int argc, char* argv[]) { int var; var= log2(16); printf("%d",var); return 0; } 

gcc prog.c (NO Error) 4

But when I pass the variable to the log2 (var) function, it gives an undefined error reference to `log2 'I need to link the library, i.e. -lm

 #include <stdio.h> #include<math.h> int main(int argc, char* argv[]) { int var,i; i= log2(var); printf("%d",i); return 0; } 

Gives an error

 undefined reference to `log2' 
+7
source share
1 answer

In the first code snippet, the compiler replaces log2(16) constant 4 . The compiler usually optimizes constant math in this way. This is the reason you do not see the error.

See generated code for confirmation. This is for your first version:

 main: pushl %ebp movl %esp, %ebp andl $-16, %esp subl $32, %esp movl $4, 28(%esp) movl $.LC0, %eax movl 28(%esp), %edx movl %edx, 4(%esp) movl %eax, (%esp) call printf movl $0, %eax leave ret 

There is no call in log2. The compiler has already replaced it with constant 4 ( movl $4, 28(%esp) ).

This is for your second version:

 main: pushl %ebp movl %esp, %ebp andl $-16, %esp subl $48, %esp fildl 40(%esp) fstpl (%esp) call log2 fnstcw 30(%esp) movzwl 30(%esp), %eax movb $12, %ah movw %ax, 28(%esp) fldcw 28(%esp) fistpl 44(%esp) fldcw 30(%esp) movl $.LC0, %eax movl 44(%esp), %edx movl %edx, 4(%esp) movl %eax, (%esp) call printf movl $0, %eax leave ret 

As you can see, there is call log2 in this version. This is why -lm is required for the second version.

+7
source

All Articles