I have a strange problem when I try to compile the below minimal example. The first call to sqrt
poses no problem, but the second one raises a linker error which I don't understand because I do specify the math library when calling gcc
. When I comment the second line, it compiles/links correctly.
Here is the code:
// File wtf_sqrt.c
#include <math.h>
int main (int argc, char *argv[]) {
int x = 3; // Just an int...
sqrt(3); // This line works fine
sqrt(x); // But this one seems to give the linker trouble. Why?
return 0;
}
Here is my compilation command:
gcc -lm -o wtf_sqrt wtf_sqrt.c
And here is the error returned:
/tmp/ccgQN7y7.o: In function `main':
wtf_sqrt.c:(.text+0x1c): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status
I use gcc
version 7.5.0 on an Ubuntu 18.04 LTS. libc6-dev
is installed (proof is, sqrt
works when I use it as in the first line of main
). The code was written in gedit
, so it should not be a problem with a blank character. Not sure what other info I can give you…
At this point, I really suspect this is a problem with my config/distribution, but I wanted some external advice.