CMake library linking order
Just link lib_B
and lib_C
to lib_D
, it's worth the effort (I can tell by experience), otherwise you will have big troubles, for example if you try to install your program. lib_C
and lib_D
should have all their symbols solved when you are finished creating their library files, before linking them to any other library.
By the way, you can compact your target_link_libraries
in one line per target, like:
TARGET_LINK_LIBRARIES(exec lib_A lib_D)
And, if exec doesn't depend directly on lib_D
, you can avoid linking it if you have correctly linked lib_A
to lib_D
.
Anyway, regarding Q1: even if the order is guaranteed by CMake, it is not guaranteed the way your linker will treat it, you are going to suffer pain if you rely on that
user2301299
Updated on June 17, 2022Comments
-
user2301299 almost 2 years
I have following libraries
lib_A
,lib_B
,lib_C
,lib_D
. I am doing something like this in my CMake files (order is important):ADD_LIBRARY(lib_A)
ADD_LIBRARY(lib_B)
ADD_LIBRARY(lib_C)
ADD_LIBRARY(lib_D)
TARGET_LINK_LIBRARIES(lib_B lib_C)
TARGET_LINK_LIBRARIES(lib_A lib_B)
ADD_EXECUTABLE(Exec)
TARGET_LINK_LIBRARIES(exec lib_A)
TARGET_LINK_LIBRARIES(exec lib_D)
This results in following linker command.
linker -llib_A -llib_D -llib_B -llib_C
Q1. Why are
lib_B
andlib_C
afterlib_D
?Q2. When I change CMake a little bit and do something like this:
TARGET_LINK_LIBRARIES(lib_A lib_D)
TARGET_LINK_LIBRARIES(exec lib_A)
then linking order is like this:
linker -llib_A -llib_B -llib_C -llib_D
Here,
lib_B
andlib_C
are beforelib_D
. It means thattarget_link_libraries
works differently for executable targets and library targets. Am I right?The problem here is that
lib_B
andlib_C
also depend onlib_D
, but I don't want to maketarget_link_libraries(lib_B lib_D)
andtarget_link_libraries(lib_C lib_D)
, because I have more of such cases, and I would have to do it manually for each library. Of course doing like in Q2 solves the problem but:Q3 - Is this order guaranteed somehow by CMake or it is just a fortuity?
Thank you
-
user2301299 almost 11 yearsThank you for answers. I have decided that I will add the dependency automatically to each library. It will solve another issue. Some of those libraries are shared across a number of executables. Keeping dependencies at the level of each library, i don't have to worry about unresolved symbols at the time of linking those executables.