I am porting an AutoTools project to CMake.
What AutoTools does:
What I've managed to do with CMake:
add_library(staticfoo <src>)
add_library(sharedfoo SHARED <src>)
and link them - target_link_libraries(sharedfoo staticfoo)
target_link_libraries(exe sharedfoo)
, but that dragged the static libraries in again, too.So, the resulting link command for the executable has static libs in addition to shared. Which doesn't correspond to the command generated by AutoTools project.
I've tried target_link_libraries(sharedfoo PRIVATE staticfoo)
, but that doesn't get the symbols from the static lib into the interface of the shared lib.
How to get the symbols without that 'transitive' behavior?
(in platform-independent way)
You can't statically link a shared library (or dynamically link a static one).
Static libraries take longer to execute, because loading into the memory happens every time while executing. While Shared libraries are faster because shared library code is already in the memory.
As I know, CMake doesn't allow to mix STATIC and SHARED libraries.
If your staticfoo
library is used solely as part of other libraries/executables, you can define it as
add_library(staticfoo OBJECT <src>)
and use then as some sort of sources when build other library:
add_library(sharedfoo SHARED <src> $<TARGET_OBJECTS:staticfoo>)
For more info see documentation on add_library.
To resolve this case you need to do few things:
-fPIC
, so they'll contain a relocatable code (which would be a part of a shared library later)PRIVATE <static libs>
when linking your shared library, so the linker command line for your executable wouldn't have any static libsIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With