Reputation: 9025
I'm designing a collection of libraries that can be linked in my other C++ projects. In order to make the collection easy to use I want to either be able to link to individual libraries, or link to one master library that contains all of the others. How can I specify this in a CMakeLists.txt
file?
For example:
add_library(library1 SHARED
file1.cpp
file2.cpp
)
add_library(library2 SHARED
file3.cpp
file4.cpp
)
# Define a master library that contains both of the others
add_library(master_library SHARED
library1
library2
)
Is there a proper way to get this functionality with CMake?
This question is not a duplicate of: CMake: Is it possible to build an executable from only static libraries and no source?
This has to do with shared libraries only and has nothing to do with static libraries or executables.
Upvotes: 7
Views: 10419
Reputation: 14951
If all you want is a convenient target for use by others and don't care about whether you have one or multiple libraries, cmake can do that with an interface library:
add_library(library1 SHARED
file1.cpp
file2.cpp
)
add_library(library2 SHARED
file3.cpp
file4.cpp
)
add_library(master_library INTERFACE)
# Link the master library with the other libraries
target_link_libraries(master_library INTERFACE
library1
library2
)
Then in another location if you have
target_link_libraries(my_executable PRIVATE
master_library
)
my_executable
will link against library1
and library2
Upvotes: 5
Reputation: 9025
This solution seemed to work.
add_library(library1 SHARED
file1.cpp
file2.cpp
)
add_library(library2 SHARED
file3.cpp
file4.cpp
)
# dummy file is required to avoid a cmake error, but this
# "dummy" file serves no other purpose and is empty.
add_library(master_library SHARED
dummy.cpp
)
# Link the master library with the other libraries
target_link_libraries(master_library
library1
library2
)
After doing this, I was able to compile and link code using ONLY the master library.
Upvotes: 12
Reputation: 249592
Just make a function in your project:
function(link_all_libs TARGET)
target_link_libraries(TARGET library1 library2)
endfunction(link_all_libs)
Now you can simply:
link_all_libs(myapp)
Upvotes: -1