GCC libm not working

I have a c program that calls sin, cos and acos. When I compile, I get the following errors:

/tmp/ccDfW98S.o: In function `zip_search': main.c:(.text+0xf30): undefined reference to `sin' main.c:(.text+0xf45): undefined reference to `sin' main.c:(.text+0xf66): undefined reference to `cos' main.c:(.text+0xf7b): undefined reference to `cos' main.c:(.text+0xf9c): undefined reference to `cos' main.c:(.text+0xfc6): undefined reference to `acos' collect2: ld returned 1 exit status 

I know this is common when you do not use the -lm gcc flag. I am using this flag. I invoke GCC as follows:

 gcc -o zipcode-server -lm main.c 

When I compile on one of my computers, this works fine. The only difference I can think of is that it does not work on x86_64, and the computer on which it works is i686. Both are Ubuntu. The libm.a file is present on the computer on which it does not work, and I have no errors saying that it cannot be found. What could be the reason for this?

+8
c linux
source share
1 answer

You should put -lm after main.c

In general, if you have several libraries, they should be recorded in the order of their use. For example, if library A uses library B , you must have -lA -lB .

In your case, the object file resulting from compiling main.c uses the m library, and so -lm should follow it.


For the curious, this is mainly for efficiency reasons. Using this scheme, the linker can resolve currently unknown characters with each new library visible in the argument list and collect new unknown characters from this library along the way. This means that the linker can visit the libraries one by one and, therefore, match unknown characters with the small number of characters provided by each library.

In contrast, the linker can load characters from all libraries at the same time, and then start matching unknown characters. In this case, however, the linker needs to deal with a much larger number of characters, increasing both the amount of memory and the linker runtime.

Since libraries can always be declared to the linker in the correct order of their dependencies, 1 there is no reason for the linker to choose an inefficient way.

1 Libraries usually have one-way relationships, in the sense that one uses the other. Cyclic dependencies between libraries are rare, if they exist at all, but can still be used with this model, repeating some libraries that will be re-inspected.

+18
source share

All Articles