CMake: correctly linking system library using gcc

10,572

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.

Share:
10,572
mirkokiefer
Author by

mirkokiefer

Updated on June 08, 2022

Comments

  • mirkokiefer
    mirkokiefer almost 2 years

    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?

  • mirkokiefer
    mirkokiefer about 11 years
    I think you are right - gcc seems to drop libraries during the link if they are not supplied after the binary. If I change the command to target_link_libraries(myapp mylib m) it works!
  • Patrick B.
    Patrick B. about 11 years
    Did you use make VERBOSE=1 with clang?
  • Fraser
    Fraser about 11 years
    You should probably mark @Patrick B.'s answer as correct then :-)