$> man cmake | grep -A6 '^ *BUILD_SHARED_LIBS$'
BUILD_SHARED_LIBS
Global flag to cause add_library to create shared libraries if on.
If present and true, this will cause all libraries to be built shared unless the library was
explicitly added as a static library. This variable is often added to projects as an OPTION
so that each user of a project can decide if they want to build the project using shared or
static libraries.
# list of source files
set(libsrc source1.c source2.c)
# this is the "object library" target: compiles the sources only once
add_library(objlib OBJECT ${libsrc})
# shared libraries need PIC
set_property(TARGET objlib PROPERTY POSITION_INDEPENDENT_CODE 1)
# shared and static libraries built from the same object files
add_library(MyLib_shared SHARED $<TARGET_OBJECTS:objlib>)
add_library(MyLib_static STATIC $<TARGET_OBJECTS:objlib>)
正如前面的回答所建议的那样,将所有东西都打包在同一个编译器中是可能的,但是我建议不要这样做,因为到最后,这是一种只适用于简单项目的黑客技术。例如,在某些情况下,您可能需要为库的不同版本设置不同的标志(尤其是。在 Windows 上,标志通常用于在导出符号之间切换)。或者如上所述,您可能希望将 .lib文件放到不同的目录中,这取决于它们是对应于静态库还是共享库。每个障碍都需要一个新的黑客。