skip to content

In CMake, core is built with target_compile_definitions(core PRIVATE CORE_PROFILING) and core.hpp adds a struct member under #ifdef CORE_PROFILING; why does the app misbehave?

level: seniorimportance: should knowfreq 38%

answer

  1. who compiles core.hpp
  2. two translation units, two layouts
  3. the One Definition Rule
  4. definitions that shape public headers

basics

~20 s

PRIVATE gives CORE_PROFILING to core's own sources only, so the app compiles core.hpp without it and sees a smaller struct. The two sides disagree on the layout, which is an ODR violation with undefined behaviour; the definition must be PUBLIC.

solid answer

~40 s

A `PRIVATE` definition lands in `core`'s `COMPILE_DEFINITIONS` and nowhere else. Every consumer that includes `core.hpp` compiles it without `CORE_PROFILING`, so `app` sees `Stats` with one member while `core.cpp` sees two. In a run of exactly this setup, `sizeof(core::Stats)` was 4 in `app` and 16 inside `core`. Nothing warns: each translation unit is compiled separately and the linker does not compare class layouts. In C++ terms the class has two different definitions, an ODR violation that makes the program ill-formed with no diagnostic required, so fields get read at the wrong offsets and memory past the smaller object gets written. The fix is `target_compile_definitions(core PUBLIC CORE_PROFILING)`, or keeping layout-changing switches out of public headers altogether.

code

cmake · 9 lines
cmake
add_library(core STATIC core/core.cpp)
target_include_directories(core PUBLIC core/include)
target_compile_definitions(core PRIVATE CORE_PROFILING)   # bug: header depends on it

add_executable(app app.cpp)
target_link_libraries(app PRIVATE core)

# fix:
# target_compile_definitions(core PUBLIC CORE_PROFILING)

go deeper

for a junior

Recall that a PRIVATE definition is seen only by the library's own source files, never by code that includes its headers.

for a middle

Explain how the same header compiles to two layouts in two translation units and why PUBLIC makes them agree.

for a senior

Diagnose memory corruption that appears only across a library boundary by checking which macros the public headers test against the definitions' scope keywords.

for a principal

Set the rule that public headers never depend on PRIVATE configuration, and prefer generated configuration headers or layouts that hide optional data.

## The setup `core` is a library with a public header `core/core.hpp`: ```cpp #pragma once namespace core { struct Stats { int frames = 0; #ifdef CORE_PROFILING long long ticks = 0; #endif }; int stats_size(); } ``` Its CMake code turns profiling on with `target_compile_definitions(core PRIVATE CORE_PROFILING)`, and `app` links `core`. Both compile without errors and link cleanly. ## What PRIVATE actually does `target_compile_definitions` writes to one of two properties: | Keyword | `COMPILE_DEFINITIONS` (core's own sources) | `INTERFACE_COMPILE_DEFINITIONS` (consumers) | |---|---|---| | `PRIVATE` | yes | no | | `INTERFACE` | no | yes | | `PUBLIC` | yes | yes | So `core.cpp` is compiled with `-DCORE_PROFILING`, while `app.cpp`, which includes the same header, is not. The header is the shared part of the contract, and each side now reads a different version of it. ## Why it goes wrong silently Each `.cpp` file is a separate **translation unit**, compiled independently. In `core.cpp`, `Stats` has two members; in `app.cpp`, it has one. A run of this exact project printed `app sizeof=4 core sizeof=16`. The linker matches symbol names, not class layouts, so nothing reports the mismatch. In C++ terms the program now has two different definitions of `core::Stats`, which breaks the **One Definition Rule**. That makes the program ill-formed with no diagnostic required, so its behaviour is undefined. Typical symptoms: - a field read through a `Stats&` passed from `app` into `core` returns garbage, because `core` reads `ticks` past the end of `app`'s smaller object; - `core` writes `ticks` into memory `app` uses for something else, which shows up later as an unrelated crash; - inline functions in the header compiled differently on each side, with the linker keeping one arbitrary copy. ## The fixes 1. **Make the definition `PUBLIC`.** Every target that links `core` then compiles `core.hpp` the same way `core` does. This is the minimal fix. 2. **Keep layout-changing switches out of public headers.** Store the extra data behind a pointer, or in a type only `core.cpp` sees, so the macro becomes a private implementation detail and `PRIVATE` is correct again. 3. **Generate the setting into a header.** A configuration header produced at configure time and included by `core.hpp` carries the value with the header itself, so no consumer can compile it differently. `INTERFACE` is wrong here: consumers would get the macro and `core` itself would not, which is the same mismatch in the other direction. ## The same trap elsewhere The rule is general: **a definition or option that changes what a public header means must reach every consumer.** Other examples that bite real projects: - libstdc++'s debug mode, `-D_GLIBCXX_DEBUG`, changes the sizes of standard containers such as `std::vector`, so its documentation warns that debug and non-debug code may be linked only if no container instantiation is passed between them; turning it on for one library with `PRIVATE` breaks exactly that rule; - a feature macro that adds or removes virtual functions in a public class; - a packing pragma or alignment macro applied conditionally in a header. A useful review check when reading CMake code: for every `PRIVATE` definition, search the library's public headers for that macro. A hit means the keyword is wrong or the header needs restructuring. ## Finding it in a real codebase The symptom rarely points at CMake: a field holds garbage, a destructor crashes, or a value is correct in `core`'s logs and wrong in the caller. A methodical path: 1. **Suspect a layout mismatch** when corruption appears only where objects cross from one target into another. 2. **Compare the compile commands.** `compile_commands.json` (from `CMAKE_EXPORT_COMPILE_COMMANDS`) or a verbose build shows the `-D` flags each translation unit received; a flag present for `core.cpp` and absent for `app.cpp` is the lead. 3. **Print the size on both sides.** A `static_assert(sizeof(core::Stats) == ...)` in the header, or a logged `sizeof` in each target as in the run above, confirms the mismatch in seconds. 4. **Fix the scope keyword or the header**, then rebuild everything that includes it, since every consumer object file was compiled with the old layout.

  • Why does neither the compiler nor the linker report the mismatched struct?
    The compiler sees one translation unit at a time, and each is internally consistent. The linker resolves symbols by name, and `Stats` itself is not a symbol whose size it checks. C++ classifies this ODR violation as no diagnostic required. GCC's `-Wodr`, on by default, can report such violations during link-time optimization, but nothing in a normal build guarantees a warning.
  • When is a PRIVATE compile definition the right choice for a library?
    When only the library's own `.cpp` files test the macro: selecting an algorithm, enabling internal logging, or naming an export macro while building a shared library. If any public header tests it, consumers compile that header differently and the definition must be `PUBLIC`.

  • PRIVATE definitions can never affect a library's consumers
  • The linker would report a struct whose size differs between files
  • INTERFACE is the fix because consumers are the ones missing the macro
  • An ODR violation always crashes immediately at startup