The first thing to know: one doesn't link a static library - one uses an archiver (ar
on Linux), which just puts all object files into one archive - libXXX.a
It's not very usual to construct a static library from other static libraries, but not impossible (though I don't know exactly how to do it with cmake, but if everything else fails - you still have add_custom_command
).
Let's assume you have two static libs libA.a
and libB.a
and would like to merge them into a combined library libALL.a
. The most straight forward way would be to unpack both archives (remember static libraries are just archives after all), and pack all unpacked object-files into a new archive/static library libALL.a
(please refer to man pages of ar
for more information about used options):
ar -x libA.a
ar -x libB.a
ar -crs libALL.a *.o
Another possibility would be to use a mri-script for ar
, using it we would avoid all unpacked object files laying around (and it is more robust, because not all object-files have *.o
-extension):
ar -M <<EOM
CREATE libALL.a
ADDLIB libA.a
ADDLIB libB.a
SAVE
END
EOM
Some people ran in addition
ar -s libALL.a
or the equivalent
ranlib libALL.a
to ensure that an archive index is created (this is the only thing that differentiate a static library from a simple archive), but the archive index is built per default anyways (it was at least the case for ar
-versions I have used so far).
One more note: The intuitive (and more similar to the VisualS tudio command lib.exe /OUT:libALL.lib libA.lib libB.lib
)
ar -crs libALL.a libA.a libB.a
does not produces an archive which can be used by the linker - ar
expects object-files and is not smart enough to look into the sub-archives to find them.
Shared libraries are linked. Furthermore, shared libraries need Position Independent Code, that means all object files must have been compiled with options -fPIC
.
Often a library provides two versions:
- static, compiled without
-fPIC
- shared, compiled with
-fPIC
Being compiled without -fPIC
, the static version is slightly more efficient. It also assures that a static library isn't used as dependency in a shared library, which could lead to violations of One Definition Rule.
As a rule of thumb, shared libraries should depend on other shared libraries and not static libraries.
Clearly, you could recompile all your static libraries with -fPIC
and link them together to a single shared library - but I would not recommend it.