Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMake: correctly linking system library using gcc

Tags:

gcc

cmake

clang

I have a static libary mylib that depends on the math library.

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

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

But if I do the linking directly with the executable it fails when using gcc (with clang it works!)

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

Why does this make any difference?
I thought that it is anyway not possible to link libraries together?

like image 984
mirkokiefer Avatar asked Mar 03 '13 02:03

mirkokiefer


1 Answers

When using cmake's target_link_libraries it does not mean you will link anything. It rather will create a dependency between a target and a library of type/action link.

I guess that the actually build line of the first example will result in something like that:

gcc -o myapp myapp.o -lmylib -lm

and the second one

gcc -o myapp myapp.o -lm -lmylib

. If mylib has references to m the second example (might) not link.

Try to run make VERBOSE=1 and study the command-line of the link-process to really understand what's happening. The linker of clang is maybe intelligent and waits for all calls to be linked before actually dropping a library during the link-process.

like image 51
Patrick B. Avatar answered Nov 15 '22 11:11

Patrick B.