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.
Shahbaz
source share