I was reading a book on GCC. It said only the standard library is linked by default for any C program. Since the pow()
is not in the standard library, I will have to link to it using the -lm
flag. However, when I compiled, I simply used:
gcc hello.c -o hello
and it still worked..
And there is another similar problem, the book also said that if you have printf("%f\\n", 4);
in your C program and if you compile WITHOUT -Wall
option, no warning will be issued. However, I tried compiling it without the -Wall
option but I still got a warning:
hello.c:6:2: warning: format '%f' expects argument of type 'double', but argument 2 has type 'int' [-Wformat]
Why is this? The book said I have to supply -lm
and -Wall
in order to make my program compiled and get the warning but I did not use either of them but I still got my program compiled and got the warning?
Thank you!
A bit more information based on some experimentation.
Consider this program:
#include <stdio.h>
#include <math.h>
int main(void) {
#ifdef CONSTANT
double x = pow(2.0, 10.0);
#else
double expon = 10.0;
double x = pow(2.0, expon);
#endif
printf("x = %f\n", x);
return 0;
}
On Ubuntu, when I compile it with
$ gcc c.c -o c
it complains about an undefined reference to pow
; adding -lm
corrects it.
But this:
$ gcc -DCONSTANT c.c -o c
compiles and links without error, replacing the pow()
call with a constant 1024.0
. But this:
$ gcc -fno-builtin -DCONSTANT c.c -o c
complains again about the undefined reference to pow
.
Conclusion: gcc uses the built-in implementation of pow
only when the result can be determined at compile time. Otherwise it generates an explicit call to the pow()
function, which requires linking with -lm
.
Note also that this depends on the way the C library is organized (the library is provided separately; it's not part of gcc). On Cygwin, which uses newlib rather than the glibc used on Ubuntu, the -lm
option is not needed; apparently the math routines are an integral part of the standard library rather than being provided separately. (gcc on Cygwin still accepts the -lm
option.)
GCC supplies several standard library functions as built-ins :
GCC provides a large number of built-in functions other than the ones mentioned above. Some of these are for internal use in the processing of exceptions or variable-length argument lists and will not be documented here because they may change from time to time; we do not recommend general use of these functions.
The remaining functions are provided for optimization purposes.
If you look at the list of built-ins, you'll see that pow
is one of them.
If you add -fno-builtin
to your compiler options, you should get the linker error that you're expecting.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.