Field Notes: Anti-Patterns & Their Fixes
Most CMake pain in real projects comes from a handful of habits from the CMake 2.x era, copied from old tutorials and Stack Overflow answers. Each one below is shown failing in a real session, then fixed.
1. Directory-wide include_directories / link_libraries / add_definitions
include_directories(), link_libraries(), add_definitions() and add_compile_options() apply to every target in the directory and its subdirectories, including targets that shouldn't see them. The damage is hidden: things compile by accident, until someone moves a target into another directory.
mkdir -p leak/libs/net leak/apps && cd leak
mkdir -p libs/net/include/net && echo '#pragma once
inline int net_port() { return 8080; }' > libs/net/include/net/net.hpp
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Leak LANGUAGES CXX)
include_directories(libs/net/include) # anti-pattern: global include path
add_definitions(-DNET_DEBUG) # anti-pattern: global definition
add_executable(server apps/server.cpp) # really uses net
add_executable(calc apps/calc.cpp) # never should have seen net
CM
echo '#include <net/net.hpp>
int main() { return net_port() == 8080 ? 0 : 1; }' > apps/server.cpp
echo '#include <net/net.hpp> // an accidental dependency nobody noticed
int main() { return 0; }' > apps/calc.cpp
cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null
cmake --build build -v | awk '/c\+\+ .* -c /{f=$NF; sub(/.*\//,"",f); d=""; for(i=1;i<=NF;i++) if($i ~ /^-[DI]/) d=d" "$i; print f ":" d}'server.cpp: -DNET_DEBUG -I/home/learner/leak/libs/net/include
calc.cpp: -DNET_DEBUG -I/home/learner/leak/libs/net/include
Both programs got -DNET_DEBUG and the net include path, so calc's accidental #include <net/net.hpp> compiles. The fix: make net a target that carries its own usage requirements, and link it only where it is used. Now the accidental dependency is a compile error, as it should be:
mkdir -p leak/libs/net/include/net leak/apps && cd leak
echo '#pragma once
inline int net_port() { return 8080; }' > libs/net/include/net/net.hpp
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Leak LANGUAGES CXX)
add_library(net INTERFACE)
target_include_directories(net INTERFACE libs/net/include)
target_compile_definitions(net INTERFACE NET_DEBUG)
add_executable(server apps/server.cpp)
target_link_libraries(server PRIVATE net)
add_executable(calc apps/calc.cpp)
CM
echo '#include <net/net.hpp>
int main() { return net_port() == 8080 ? 0 : 1; }' > apps/server.cpp
echo '#include <net/net.hpp>
int main() { return 0; }' > apps/calc.cpp
cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null
cmake --build build 2>&1 | grep -E 'error|^\[' | grep -v '^\[.*Linking'[1/4] Building CXX object CMakeFiles/server.dir/apps/server.cpp.o
[2/4] Building CXX object CMakeFiles/calc.dir/apps/calc.cpp.o
/home/learner/leak/apps/calc.cpp:1:10: fatal error: net/net.hpp: No such file or directory
The same goes for link_libraries() (use target_link_libraries) and add_definitions/add_compile_options (use the target_* versions; a project-wide setting belongs in an INTERFACE target like project_warnings, see Compile Features).
2. Globbing sources
file(GLOB SOURCES src/*.cpp) # anti-pattern
add_executable(app ${SOURCES})The glob runs at configure time. Add a new .cpp file and nothing tells CMake to re-run: the build silently ignores the file until someone re-configures, and you get a confusing link error instead.
mkdir -p glob/src && cd glob
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Glob LANGUAGES CXX)
file(GLOB SOURCES src/*.cpp)
add_executable(app ${SOURCES})
CM
echo 'int helper(); int main() { return helper() == 7 ? 0 : 1; }' > src/main.cpp
echo 'int helper() { return 7; }' > src/helper.cpp
cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null
cmake --build build > /dev/null && echo "first build ok"
echo "--- add a new file and use it"
echo 'int extra() { return 0; }' > src/extra.cpp
echo 'int helper(); int extra(); int main() { return helper() + extra() == 7 ? 0 : 1; }' > src/main.cpp
cmake --build build 2>&1 | grep -E 'undefined reference|FAILED|Linking' | sed 's/^.*: undefined/undefined/'
echo "--- with CONFIGURE_DEPENDS"
sed -i 's/file(GLOB SOURCES src/file(GLOB SOURCES CONFIGURE_DEPENDS src/' CMakeLists.txt
cmake -S . -B build --log-level=NOTICE > /dev/null
echo 'int more() { return 0; }' > src/more.cpp
cmake --build build | grep -E 'more|Re-running'first build ok
--- add a new file and use it
[2/2] Linking CXX executable app
FAILED: [code=1] app
undefined reference to `extra()'
--- with CONFIGURE_DEPENDS
-- GLOB mismatch!
The following files were added:
+/home/learner/glob/src/more.cpp
[1/2] Re-running CMake...
[2/6] Building CXX object CMakeFiles/app.dir/src/more.cpp.o
CONFIGURE_DEPENDS (3.12+) makes the build re-check the glob on every build and re-configure when the result changes, which fixed it. It costs a directory scan per build and doesn't work with every generator, and the CMake documentation still recommends against globbing sources. The fix most teams use: list the sources explicitly. It's one line per file, it shows up in code review when someone adds or removes a file, and it can't pick up stray files (a half-finished test_old.cpp, an editor's backup).
3. Editing CMAKE_CXX_FLAGS
set(CMAKE_CXX_FLAGS "-Wall -O2") # anti-pattern 1: overwrites the user's flags
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror") # anti-pattern 2: global, unscopedCMAKE_CXX_FLAGS belongs to the person building: it's where CXXFLAGS, distribution hardening flags and -DCMAKE_CXX_FLAGS=... arrive. Overwriting it throws their flags away; appending to it applies yours to every target, including third-party code added from source.
mkdir -p flags && cd flags
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Flags LANGUAGES CXX)
set(CMAKE_CXX_FLAGS "-Wall") # overwrites whatever the user passed
add_executable(app main.cpp)
CM
echo 'int main() { return 0; }' > main.cpp
CXXFLAGS="-fstack-protector-strong -D_FORTIFY_SOURCE=2" cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null
echo "cache (what the user asked for): $(grep '^CMAKE_CXX_FLAGS:' build/CMakeCache.txt)"
echo "compiled with: $(cmake --build build -v | sed -n 's/.*\/usr\/bin\/c++ *\(.*\) -MD .*/\1/p' | sed 's/ *-fno-diagnostics-color//')"
echo "--- fixed"
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Flags LANGUAGES CXX)
add_executable(app main.cpp)
target_compile_options(app PRIVATE -Wall) # scoped to our target, user flags kept
CM
rm -rf build
CXXFLAGS="-fstack-protector-strong -D_FORTIFY_SOURCE=2" cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null
echo "compiled with: $(cmake --build build -v | sed -n 's/.*\/usr\/bin\/c++ *\(.*\) -MD .*/\1/p' | sed 's/ *-fno-diagnostics-color//')"cache (what the user asked for): CMAKE_CXX_FLAGS:STRING=-fstack-protector-strong -D_FORTIFY_SOURCE=2
compiled with: -Wall
--- fixed
compiled with: -fstack-protector-strong -D_FORTIFY_SOURCE=2 -Wall
The user's hardening flags were in the cache but never reached the compiler in the first version. With target_compile_options, both are there: the user's flags from CMAKE_CXX_FLAGS, and the project's from the target.
4. In-source builds
cmake . in the source directory writes CMakeCache.txt, CMakeFiles/, build.ninja and every object file between your sources. They show up in git status, a second configuration (Release next to Debug) is impossible, and cleaning means hunting files down.
mkdir -p insrc && cd insrc
git init -q
printf 'cmake_minimum_required(VERSION 3.25)\nproject(InSrc LANGUAGES CXX)\nadd_executable(app main.cpp)\n' > CMakeLists.txt
echo 'int main() { return 0; }' > main.cpp
git add . && git commit -q -m init
cmake . -G Ninja --log-level=NOTICE > /dev/null && cmake --build . > /dev/null
echo "--- git status after an in-source build"
git status --short
echo "--- a guard at the top of CMakeLists.txt"
git clean -qfdx
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
if(CMAKE_SOURCE_DIR STREQUAL CMAKE_BINARY_DIR)
message(FATAL_ERROR "In-source builds are not allowed. Use: cmake -S . -B build")
endif()
project(InSrc LANGUAGES CXX)
add_executable(app main.cpp)
CM
cmake . -G Ninja --log-level=NOTICE 2>&1 | grep -A1 'CMake Error'
git status --short--- git status after an in-source build
?? .ninja_deps
?? .ninja_log
?? CMakeCache.txt
?? CMakeFiles/
?? app
?? build.ninja
?? cmake_install.cmake
--- a guard at the top of CMakeLists.txt
CMake Error at CMakeLists.txt:3 (message):
In-source builds are not allowed. Use: cmake -S . -B build
M CMakeLists.txt
?? CMakeCache.txt
?? CMakeFiles/
The guard stops the build, but CMake has already written CMakeCache.txt and CMakeFiles/ by the time it runs (they must be deleted by hand), so also add build/ and friends to .gitignore. Always use cmake -S . -B build; presets with a binaryDir make it automatic.
The short list
| Instead of | Use |
|---|---|
include_directories, add_definitions, link_libraries, add_compile_options |
target_include_directories, target_compile_definitions, target_link_libraries, target_compile_options |
file(GLOB …) for sources |
an explicit list (or at least CONFIGURE_DEPENDS) |
set(CMAKE_CXX_FLAGS …) |
target_compile_options / an INTERFACE warnings target / target_compile_features |
cmake . |
cmake -S . -B build, or a preset with binaryDir |
${FOO_INCLUDE_DIRS} / ${FOO_LIBRARIES} from find_package |
the package's imported target Foo::Foo |
cmake_minimum_required(VERSION 2.8) |
a current version or range (Policies & CMake 4) |
if(CMAKE_BUILD_TYPE STREQUAL Debug) |
lt;lt;CONFIG:Debug>:…> |
Test yourself
What goes wrong when a project uses file(GLOB SOURCES src/*.cpp) and someone adds a new .cpp file?
- Nothing
- The new file is ignored until CMake re-configures, because the glob ran at configure time
- CMake errors immediately
- The file is compiled twice
Why is set(CMAKE_CXX_FLAGS "-Wall") harmful?
- -Wall is deprecated
- It discards flags the user or distribution passed (CXXFLAGS, -DCMAKE_CXX_FLAGS)
- It only works with GCC
- It disables optimisation
include_directories(libs/net/include) at the top level has what effect?
- Only targets that link net get it
- Every target in that directory and below gets the include path, hiding accidental dependencies
- Nothing until install
- It is the same as target_include_directories PUBLIC