Libraries: STATIC, SHARED, OBJECT, INTERFACE
add_library() creates a library target. The keyword after the name says what kind:
| Kind | Produces (Linux) | When to use |
|---|---|---|
STATIC |
libname.a, an archive of object files copied into each program that links it |
the default choice for internal libraries |
SHARED |
libname.so (Windows .dll + import .lib, macOS .dylib), loaded at run time |
code shared by several programs, plugins hosts, distributing a binary SDK |
MODULE |
a .so that is never linked, only dlopened |
plugins |
OBJECT |
no file, just a set of .o files other targets can use |
compile once, use the objects in several targets |
INTERFACE |
nothing is built | header-only libraries, or a bundle of settings (flags, definitions) |
If you leave the keyword out, the variable BUILD_SHARED_LIBS decides: ON means SHARED, otherwise STATIC. That lets the person building choose with -DBUILD_SHARED_LIBS=ON, which is why libraries meant for others usually omit the keyword.
All five in one project
bash · try it yourself
mkdir -p kinds && cd kinds
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Kinds LANGUAGES CXX)
add_library(mathstatic STATIC math.cpp)
add_library(mathshared SHARED math.cpp)
add_library(plugin MODULE plugin.cpp)
add_library(common OBJECT common.cpp)
add_library(config INTERFACE)
target_compile_definitions(config INTERFACE APP_NAME="kinds")
add_executable(app main.cpp)
target_link_libraries(app PRIVATE mathstatic common config)
foreach(t mathstatic mathshared plugin common config app)
get_target_property(type ${t} TYPE)
message("${t}: ${type}")
endforeach()
CM
echo 'int twice(int x) { return 2 * x; }' > math.cpp
echo 'extern "C" int plugin_version() { return 3; }' > plugin.cpp
echo 'const char* banner() { return "== kinds =="; }' > common.cpp
cat > main.cpp <<'SRC'
#include <cstdio>
int twice(int);
const char* banner();
int main() { std::printf("%s %s: twice(21) = %d\n", banner(), APP_NAME, twice(21)); }
SRC
cmake -S . -B build -G Ninja --log-level=NOTICE
cmake --build build
./build/app
ls build | grep -E '\.(a|so)