Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

c++ - CMake and order dependent linking of shared libraries

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...