CMake: properly bind a system library using gcc

I have a mylib static library which depends on a math library.

If I first link mylib with math, and then with my executable, it works:

add_executable(myapp main.c) target_link_libraries(mylib m) target_link_libraries(myapp mylib) 

But if I make a link directly to the executable, it fails when using gcc (with clang it works!)

 add_executable(myapp main.c) target_link_libraries(myapp m mylib) 

Why does it matter?
I thought it was impossible to link libraries together anyway?

+6
source share
2 answers

Using cmake target_link_libraries does not mean that you are connecting anything. This will more likely create a dependency between target and a library type / action link .

I assume that the line of actually building the first example will lead to something like this:

 gcc -o myapp myapp.o -lmylib -lm 

and second

 gcc -o myapp myapp.o -lm -lmylib 

. If mylib has references to m , the second example (may) not be referenced.

Try running make VERBOSE=1 and examine the link process command line to really understand what is going on. The clang component is probably smart and expects all calls to be linked before the library is actually deleted during the link process.

+6
source

When using target_link_libraries it is important in which order you specify the linked libraries.

This does not work when using gcc (at least in version 4.0):

 target_link_libraries(myapp m mylib) 

while it works:

 target_link_libraries(myapp mylib m) 

Thus, all mylib libraries depend on what is needed after mylib.

If you track the call to the actual linker using make VERBOSE=1 , you will find this for a broken example:

 gcc main.co -o luatest -rdynamic -lm mylib.a 

and this is for the worker:

 gcc main.co -o luatest -rdynamic mylib.a -lm 

Calling clang with exactly the same parameters works in both cases!

So @PatrickB seems to be correct:

The clang component is perhaps intelligent and expects all calls to be bound before actually dropping the library during the reference process.

0
source

All Articles