I have a very similar problem to one described on the cmake mailing list where we have a project dependent on many static libraries (all built from source in individual submodules, each with their own CMakeLists.txt describing the build process for each library) that I'd like to combine into a single static library for release to the consumers. The dependencies of my library are subject to change, and I do not want to burden developers further down the chain with those changes. The neat solution would be to bundle all of the libs into one single lib.
Interestingly, the target_link_libraries
command does not combine all of the statics when setting the target to mylib
and using it like so . .
target_link_libraries(mylib a b c d)
However, bizarrely, if I make the mylib
project a submodule of an executable project, and only link against mylib
in the top level executable CMAkeLists.txt, the library does seem to be combined. I.e. mylib is 27 MB, instead of the 3MB when I set the target to only build mylib
.
There are solutions describing unpacking of the libs into object files and recombining (here, and here), but this seems remarkably clumsy when CMake seems perfectly capable of automatically merging the libs as described in the above example. It there a magic command I'm missing, or a recommended elegant way of making a release library?
You can use this function to join any number of libraries.
It has the benefits of using add_custom_command and not add_custom_target. This way, the library (and it's dependencies) are only built when needed and not every time. The drawback is the print of the generation of the dummy file.
Given the most simple working example I can think of: 2 classes,
a
andb
, wherea
depends onb
. .a.h
a.cpp
b.h
b.cpp
main.cpp
It is possible to compile these into separate static libs, and then combine the static libs using a custom target.
It also works just fine using Apple's
libtool
version of the custom target . . .Still seams as though there should be a neater way . .
If the libraries you are trying to merge are from third parties, then (following learnvst example) this code take care of possible .o file replacements (if for instance both liba and libb have a file name zzz.o)
Otherwise, if the libraries are yours, you should use CMake OBJECT libraries, that are a pretty good mechanism to get them merged.