CMake and order dependent linking of shared libraries

 ̄綄美尐妖づ 提交于 2019-12-17 22:33:20

问题


I have a few small components that I am building as shared libraries for my main application. Lets use an example of liba and libb. Each is built within their own subdirectory as follows:

add_library(liba SHARED a.cpp)

Then, in the root project folder, I need to link my main application to both.

include_directories(a)
include_directories(b)
add_executable(dummy dummy.cpp)
target_link_libraries(dummy a b)

CMake runs fine with this, and my application compiles but fails to link. The problem is that b references a. If I supply the order of the libraries while linking as

target_link_libraries(dummy b a)

The program compiles and links just fine

When this sort of system starts involving more complex inter dependency of the libraries, it starts to be impossible even if the dependencies are acyclic. How do I manage the linking step here? Is there a trick to ordering libraries for linking in CMake?


回答1:


You can specify the relationship between a and b by adding

target_link_libraries(b a)


From the docs:

Library dependencies are transitive by default. When this target is linked into another target then the libraries linked to this target will appear on the link line for the other target too.

So, if you specify a as a dependency of b in this way, you don't even need to explicitly list a in any target which depends on b, i.e. your other command can be just:

target_link_libraries(dummy b)

although it wouldn't do any harm to list a as well.




回答2:


An easy solution (especially for circular dependencies) can be to just put all your libraries in a list variable, then add that list twice (or more if necessary), like:

set(LINK_LIBS "liba libb libc")
target_link_libraries(app ${LINK_LIBS} ${LINK_LIBS})

(or just type out the list twice after each other in the target_link_libraries function)

This has worked for me quite a couple of times, but I'll admit that there might be some possible drawbacks that I'm unaware of (other than it seeming like a bit of a hack).



来源:https://stackoverflow.com/questions/12204820/cmake-and-order-dependent-linking-of-shared-libraries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!