PUBLIC, PRIVATE & INTERFACE
This is the most important lesson in the course. Modern CMake works because each target declares two sets of settings:
- its build requirements: what it needs to compile and link (properties like
INCLUDE_DIRECTORIES,COMPILE_DEFINITIONS); - its usage requirements: what anyone who links it needs (properties prefixed
INTERFACE_, likeINTERFACE_INCLUDE_DIRECTORIES).
The scope keyword in every target_* command chooses where a setting goes:
| Keyword | Goes into | Meaning |
|---|---|---|
PRIVATE |
build requirements only | "I need this, my users don't" |
INTERFACE |
usage requirements only | "my users need this, I don't" (typical for header-only libraries) |
PUBLIC |
both | "I need this, and so does anyone using me" |
The rule of thumb: does it appear in your public headers? If a header your users include needs it (an include path, a type from another library, a macro), it is PUBLIC. If only your .cpp files need it, it is PRIVATE.
A failing build
Here the library author declared the include directory PRIVATE. The library compiles fine; its user does not:
mkdir -p shapes/geometry/include/geometry shapes/geometry/src && cd shapes
cat > geometry/include/geometry/area.hpp <<'SRC'
#pragma once
double circle_area(double r);
SRC
cat > geometry/src/area.cpp <<'SRC'
#include "geometry/area.hpp"
double circle_area(double r) { return 3.14159 * r * r; }
SRC
cat > main.cpp <<'SRC'
#include <cstdio>
#include "geometry/area.hpp"
int main() { std::printf("area = %.2f\n", circle_area(2.0)); }
SRC
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Shapes LANGUAGES CXX)
add_library(geometry STATIC geometry/src/area.cpp)
target_include_directories(geometry PRIVATE geometry/include) # wrong scope
add_executable(app main.cpp)
target_link_libraries(app PRIVATE geometry)
CM
cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null
cmake --build build
echo "exit code: $?"
echo "--- fix: the header is part of the public API"
sed -i 's/geometry PRIVATE geometry/geometry PUBLIC geometry/' CMakeLists.txt
cmake --build build && ./build/app[1/4] Building CXX object CMakeFiles/geometry.dir/geometry/src/area.cpp.o
[2/4] Linking CXX static library libgeometry.a
[3/4] Building CXX object CMakeFiles/app.dir/main.cpp.o
FAILED: [code=1] CMakeFiles/app.dir/main.cpp.o
/usr/bin/c++ -fno-diagnostics-color -MD -MT CMakeFiles/app.dir/main.cpp.o -MF CMakeFiles/app.dir/main.cpp.o.d -o CMakeFiles/app.dir/main.cpp.o -c /home/learner/shapes/main.cpp
/home/learner/shapes/main.cpp:2:10: fatal error: geometry/area.hpp: No such file or directory
2 | #include "geometry/area.hpp"
| ^~~~~~~~~~~~~~~~~~~
compilation terminated.
ninja: build stopped: subcommand failed.
exit code: 1
--- fix: the header is part of the public API
[0/1] Re-running CMake...
-- Configuring done (0.0s)
-- Generating done (0.0s)
-- Build files have been written to: /home/learner/shapes/build
[1/3] Building CXX object CMakeFiles/app.dir/main.cpp.o
[2/3] Linking CXX executable app
area = 12.57
The failed compile line for main.cpp has no -I at all. After changing one word, the build re-ran CMake by itself and main.cpp compiled.
Transitive propagation
Usage requirements travel along the link graph, but only through PUBLIC and INTERFACE links. A PRIVATE link stops propagation: it is an implementation detail.
Consider app → render → math, plus render → logging:
mkdir -p chain && cd chain
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Chain LANGUAGES CXX)
add_library(math INTERFACE)
target_compile_definitions(math INTERFACE MATH_USES_FLOAT)
add_library(logging INTERFACE)
target_compile_definitions(logging INTERFACE LOG_LEVEL=2)
add_library(render STATIC render.cpp)
target_compile_definitions(render PRIVATE RENDER_INTERNAL PUBLIC RENDER_API=1)
target_link_libraries(render
PUBLIC math # render's headers use math types
PRIVATE logging) # only render.cpp logs
add_executable(app main.cpp)
target_link_libraries(app PRIVATE render)
CM
echo 'int render_frame() { return 1; }' > render.cpp
echo 'int main() { return 0; }' > main.cpp
cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null
# print each compiled file with the -D flags on its command line
cmake --build build -v | awk '/c\+\+ .* -c /{f=$NF; sub(/.*\//,"",f); d=""; for(i=1;i<=NF;i++) if($i ~ /^-D/) d=d" "$i; print f ":" d}'render.cpp: -DLOG_LEVEL=2 -DMATH_USES_FLOAT -DRENDER_API=1 -DRENDER_INTERNAL
main.cpp: -DMATH_USES_FLOAT -DRENDER_API=1
render.cppsees its ownPRIVATEandPUBLICdefinitions, plusMATH_USES_FLOATandLOG_LEVEL=2from what it links.main.cppseesRENDER_API=1(PUBLIC) andMATH_USES_FLOAT(math is a PUBLIC dependency of render), but notRENDER_INTERNALorLOG_LEVEL=2.
Getting this right keeps compile lines short, avoids accidental dependencies, and means that changing a private dependency never forces consumers to rebuild.
A runnable model
This model implements the propagation rule over a small target graph. Change the scopes and run it again to see what app ends up with:
// Each target: its own settings with a scope, and its links with a scope.
const targets = {
math: { defs: [['INTERFACE', 'MATH_USES_FLOAT']], links: [] },
logging: { defs: [['INTERFACE', 'LOG_LEVEL=2']], links: [] },
render: { defs: [['PRIVATE', 'RENDER_INTERNAL'], ['PUBLIC', 'RENDER_API=1']],
links: [['PUBLIC', 'math'], ['PRIVATE', 'logging']] },
app: { defs: [], links: [['PRIVATE', 'render']] },
};
// Usage requirements of t: its PUBLIC/INTERFACE settings, plus the usage
// requirements of everything it links PUBLIC or INTERFACE (recursively).
function usage(name) {
const t = targets[name];
const out = t.defs.filter(([s]) => s !== 'PRIVATE').map(([, d]) => d);
for (const [scope, dep] of t.links) if (scope !== 'PRIVATE') out.push(...usage(dep));
return out;
}
// What t is compiled with: its PRIVATE/PUBLIC settings, plus the usage
// requirements of everything it links (any scope).
function build(name) {
const t = targets[name];
const out = t.defs.filter(([s]) => s !== 'INTERFACE').map(([, d]) => d);
for (const [, dep] of t.links) out.push(...usage(dep));
return [...new Set(out)];
}
for (const name of ['render', 'app']) {
console.log(`${name.padEnd(7)} compiles with: ${build(name).map((d) => '-D' + d).join(' ')}`);
console.log(`${name.padEnd(7)} passes on: ${usage(name).map((d) => '-D' + d).join(' ') || '(nothing)'}`);
}render compiles with: -DRENDER_INTERNAL -DRENDER_API=1 -DMATH_USES_FLOAT -DLOG_LEVEL=2
render passes on: -DRENDER_API=1 -DMATH_USES_FLOAT
app compiles with: -DRENDER_API=1 -DMATH_USES_FLOAT
app passes on: (nothing)
The model matches the real session. Try changing ['PUBLIC', 'math'] to ['PRIVATE', 'math']: app loses MATH_USES_FLOAT, which would break it if render's headers used math types. That is exactly the bug the failing build above showed for include paths.
What propagates
Every target_* command has the same three scopes, and all of them propagate the same way:
| Command | Build property | Usage property |
|---|---|---|
target_include_directories |
INCLUDE_DIRECTORIES |
INTERFACE_INCLUDE_DIRECTORIES |
target_compile_definitions |
COMPILE_DEFINITIONS |
INTERFACE_COMPILE_DEFINITIONS |
target_compile_options |
COMPILE_OPTIONS |
INTERFACE_COMPILE_OPTIONS |
target_compile_features |
COMPILE_FEATURES |
INTERFACE_COMPILE_FEATURES |
target_link_libraries |
LINK_LIBRARIES |
INTERFACE_LINK_LIBRARIES |
target_link_options |
LINK_OPTIONS |
INTERFACE_LINK_OPTIONS |
target_sources |
SOURCES |
INTERFACE_SOURCES |
Note: For static libraries, a
PRIVATElink still appears on the final link line of the executable, because a.afile can't carry its dependencies itself. CMake records it aslt;LINK_ONLY:logging>: the library is linked, but its compile settings don't propagate.
Test yourself
Your library's public header includes <fmt/format.h>. How should the library link fmt?
- PRIVATE
- PUBLIC
- INTERFACE
- It doesn't matter
A header-only library declares its include directory with which scope?
- PRIVATE
- PUBLIC
- INTERFACE
- GLOBAL
render links logging PRIVATE. app links render. Does app get logging's compile definitions?
- Yes
- No, a PRIVATE link stops propagation of usage requirements
- Only in Debug
- Only if logging is shared