ISO C++20 Flags, CMake AUTOMOC & Translation-Unit Hygiene

Pin every Qt 6.8 HMI target to strict ISO C++20 flags and target-scoped CMake properties so moc, uic, and rcc code generation stays deterministic across incremental builds.

25 minfree previewLinux 6.12→ module 1 lab
What you'll learn
  • Configure target-scoped CMake 3.28+ properties enforcing strict ISO C++20 without GNU extensions alongside AUTOMOC, AUTOUIC, and AUTORCC.
  • Diagnose missing vtable linker errors triggered when Q_OBJECT classes live privately inside .cpp files or outside AUTOMOC target sources.
  • Quantify preprocessor and incremental rebuild fan-out reductions achieved by replacing <QtWidgets> umbrella includes with forward declarations.

Why Legacy Global Build Macros Break Incremental Qt 6 Builds

Industrial HMIs built on Qt 6.8 LTS require at least C++17 and gain concepts, std::span, and three-way comparisons under strict ISO C++20 (-std=c++20). Legacy qmake .pro projects and older CMake files often rely on directory-wide INCLUDEPATH +=, include_directories(), or add_definitions(). Those global mutations leak widget macros, -fPIC settings, and relaxed warning flags into pure C++20 protocol libraries and unit-test binaries in the same workspace.

Before g++ compiles any QObject translation unit, three code generators execute inside the build graph. moc scans class declarations for Q_OBJECT or Q_GADGET and emits C++ meta-object tables; uic lowers Designer .ui XML layouts into ui_*.h headers; and rcc packs .qrc icons or shaders into static C++ byte arrays. Understanding exactly where CMake places those generated files eliminates baffling undefined reference to vtable link failures during bring-up.

fig_m01_l01_a.svg — Target-scoped CMake properties isolate moc, uic, and…

Figure 1.1a. Target-scoped CMake properties isolate , uic, and rcc generation per binary while keeping strict ISO C++20 flags off vendor headers.

mental model: Think of a target-scoped CMake build graph like a keyed CNC machining fixture on an assembly line: raw castings (panel.hpp, panel.ui, icons.qrc) pass through dedicated prep stations (moc, uic, rcc) whose output jigs lock solely onto one part number (ksa_hmi), rather than dumping unlabelled shims across the entire factory floor.

Where it stops working: Physical fixtures visibly jam when mismatched bolts are mixed, whereas combining static C++ archives compiled under incompatible standard flags or missing Q_OBJECT meta-tables passes object compilation quietly and explodes only during final ELF symbol resolution.

definition ( and Imported CMake Targets): CMAKE_AUTOMOC (activating target property AUTOMOC ON) instructs CMake to synthesize a <target>_autogen pre-build rule that scans target headers and sources for Q_OBJECT, Q_GADGET, or Q_NAMESPACE, invokes Qt's Meta-Object Compiler (moc), and bundles public header outputs into mocs_compilation.cpp. Imported targets (Qt6::Core, Qt6::Gui, Qt6::Widgets) are read-only CMake graph nodes exported by Qt6Config.cmake carrying exact shared-library paths alongside INTERFACE_INCLUDE_DIRECTORIES and INTERFACE_COMPILE_FEATURES.

ast_m01_l01.svg — Use target-scoped CMake properties, forward…step 1/4
  1. Step 1. Lock CXX_STANDARD 20, CXX_STANDARD_REQUIRED ON, and CXX_EXTENSIONS OFF directly on the HMI target.
  2. Step 2. Enable AUTOMOC, AUTOUIC, and AUTORCC on the target and list headers explicitly inside add_executable.
  3. Step 3. Replace mega-header #include <QtWidgets> directives with class forward declarations in every .hpp file.
  4. Step 4. Append #include '<stem>.moc' at the end of any .cpp file that defines a private Q_OBJECT helper class.

Figure 1.1b. Use target-scoped CMake properties, forward declarations, and explicit .moc includes.

Inside Autogen Artifact Layout and Header Dependency Fan-Out

When Ninja or GNU Make builds target ksa_hmi, CMake creates ksa_hmi_autogen/include/ for generated headers (ui_panel_window.h and inline panel_window.moc) plus ksa_hmi_autogen/mocs_compilation.cpp, which #includes moc_panel_window.cpp for every header-declared Q_OBJECT. Because mocs_compilation.cpp is a separate translation unit, any helper class PollWorker : public QObject { Q_OBJECT }; written privately inside panel_window.cpp is completely invisible to mocs_compilation.cpp. Including "panel_window.moc" at the bottom of panel_window.cpp inlines that generated moc body directly where PollWorker is complete.

Header discipline matters just as much on multi-core build servers and embedded cross-toolchains. Pulling #include <QtWidgets> inside panel_window.hpp forces the C++ preprocessor to open hundreds of indirect headers—exceeding 150,000 preprocessed lines—in every .cpp file that touches PanelWindow. Because sizeof(QPushButton *) is always 8 bytes on x86_64 and 4 bytes on 32-bit ARMv7-A, forward-declaring class QPushButton; in panel_window.hpp keeps header parsing tiny and confines widget header dependencies to panel_window.cpp.

fig_m01_l01_b.svg — Separating header moc compilation, inline .moc…

Figure 1.1b. Separating header moc compilation, inline .moc includes, ui_*.h forms, and qrc_*.cpp arrays prevents mystery link errors.

Build MechanismLegacy .pro / Global CMakeModern Target CMake 3.28+Impact on HMI Codebase
Standard PinningCMAKE_CXX_STANDARD mutated globally with GNU extensionsCXX_STANDARD 20, CXX_STANDARD_REQUIRED ON, CXX_EXTENSIONS OFFIdentical ISO C++20 semantics across GCC and Clang
Include & Flag Scopeinclude_directories() leaks paths to all subdirectoriestarget_link_libraries(app PRIVATE Qt6::Widgets)Unit tests and core libraries stay free of GUI flags
Meta-Object WiringManual qt_wrap_cpp() lists drifting out of syncAUTOMOC ON + explicit .hpp files in add_executableZero stale moc tables when adding Q_OBJECT
Widget Header Style#include <QtWidgets> inside public .hpp headersForward-declare class QLabel; in .hpp; include in .cppCuts incremental compile fan-out by an order of magnitude
learner@ksa: ~/gl-q01/m01-l01
learner@ksa:~/gl-q01/m01-l01$ bat -H 6 -H 14 CMakeLists.txt File: CMakeLists.txt    cmake_minimum_required(VERSION 3.28)    project(ksa_hmi VERSION 1.0.0 LANGUAGES CXX)        find_package(Qt6 6.8 REQUIRED COMPONENTS Core Gui Widgets Test)      add_executable(ksa_hmi        src/main.cpp        src/panel_window.hpp        src/panel_window.cpp        src/panel_window.ui        resources/icons.qrc    )      set_target_properties(ksa_hmi PROPERTIES        CXX_STANDARD 20        CXX_STANDARD_REQUIRED ON        CXX_EXTENSIONS OFF        AUTOMOC ON        AUTOUIC ON        AUTORCC ON    )        target_compile_options(ksa_hmi PRIVATE        -Wall -Wextra -Werror -pedantic    )        target_link_libraries(ksa_hmi PRIVATE        Qt6::Core        Qt6::Gui        Qt6::Widgets    )
  1. Listing src/panel_window.hpp and .ui/.qrc explicitly gives cmake_autogen an exact dependency manifest.
  2. CXX_STANDARD_REQUIRED ON plus CXX_EXTENSIONS OFF guarantees strict -std=c++20 without -std=gnu++20 drift.
cmake-qt(7) at a glance — GL-Q01
cmake-qt(7)                 GL-Q01 Quick Reference                 cmake-qt(7) NAME       cmake-qt - CMake target properties for Qt 6 moc, uic, and rcc       automation SYNOPSIS       find_package(Qt6 6.8 REQUIRED COMPONENTS Core Gui Widgets)       set_target_properties(<tgt> PROPERTIES AUTOMOC ON AUTOUIC ON AUTORCC       ON) target_link_libraries(<tgt> PRIVATE Qt6::Core Qt6::Gui       Qt6::Widgets) DESCRIPTION       AUTOMOC scans target headers (.h/.hpp) for Q_OBJECT/Q_GADGET and       compiles mocs_compilation.cpp. If a .cpp file declares a private       Q_OBJECT class, end that file with #include "<stem>.moc". AUTOUIC       compiles <name>.ui into ui_<name>.h. AUTORCC compiles .qrc manifests       into C++ static byte arrays. DIAGNOSTICS       "undefined reference to vtable for <Class>": 1. Header was added with       Q_OBJECT without re-running CMake / autogen scan. 2. Private Q_OBJECT       in <stem>.cpp is missing #include "<stem>.moc". Kernel Systems Academy                 Lesson 1.1                  cmake-qt(7) GL-Q01 quick reference · full manual page: man 7 cmake-qt 

Modeling CMake Autogen and Rebuild Fan-Out in Host C++20

Even on a headless CI container without full X11/Wayland packages installed, we can verify every cmake_autogen routing rule and header fan-out invariant in pure ISO C++20. In verify.cpp below, audit_cmake_target() inspects a target's standard flags and source list: it routes header Q_OBJECT declarations to mocs_compilation.cpp, requires a matching #include "<stem>.moc" whenever Q_OBJECT appears in a .cpp file, and rejects GNU extension drift.

Second, estimate_preprocessed_kloc() models a 6-unit HMI project comparing a header that includes <QtWidgets> (~140 kLOC preprocessed per client .cpp) against a forward-declared header (~4 kLOC per client .cpp, plus <QtLabel>/<QPushButton> only inside the widget's own implementation unit). Host execution proves our build-graph rules deterministically before cross-compiling against a target ARMv7-A Qt 6 sysroot.

learner@ksa: ~/gl-q01/m01-l01
learner@ksa:~/gl-q01/m01-l01$ bat -H 28 -H 48 verify.cpp File: verify.cpp    #include <cassert>    #include <cstdio>    #include <string>    #include <string_view>    #include <vector>        namespace hmi_build {        struct SourceUnit {        std::string path;        bool has_q_object;        bool has_dot_moc_include;        bool pulls_umbrella_qtwidgets;        int client_tus;    };        struct AuditReport {        int moc_header_jobs = 0;        int moc_inline_jobs = 0;        int missing_moc_errors = 0;        int umbrella_violations = 0;        int estimated_kloc = 0;    };        static bool ends_with(std::string_view s, std::string_view suffix) noexcept {        return s.size() >= suffix.size() &&               s.substr(s.size() - suffix.size()) == suffix;  }        static AuditReport audit_cmake_target(const std::vector<SourceUnit> &units,                                          int cxx_std, bool std_required,                                          bool gnu_extensions) {        assert(cxx_std >= 20 && std_required && !gnu_extensions);        AuditReport rep{};        for (const auto &u : units) {            const bool is_hdr = ends_with(u.path, ".hpp");            const bool is_src = ends_with(u.path, ".cpp");            if (is_hdr) {                if (u.pulls_umbrella_qtwidgets) {                    ++rep.umbrella_violations;                    rep.estimated_kloc += u.client_tus * 140;                } else {                    rep.estimated_kloc += u.client_tus * 4 + 18;                }            }            if (!u.has_q_object) {                continue;          }            if (is_hdr) {                ++rep.moc_header_jobs;            } else if (is_src) {                if (u.has_dot_moc_include) {                    ++rep.moc_inline_jobs;                } else {                    ++rep.missing_moc_errors;                }            }        }        return rep;    }        } // namespace hmi_build        int main() {        using hmi_build::SourceUnit;        const std::vector<SourceUnit> clean_hmi = {            {"panel_window.hpp", true, false, false, 6},            {"panel_window.cpp", true, true, false, 0},            {"alarm_strip.hpp", true, false, false, 6},            {"main.cpp", false, false, false, 0},        };        const auto ok = hmi_build::audit_cmake_target(clean_hmi, 20, true, false);        assert(ok.moc_header_jobs == 2 && ok.moc_inline_jobs == 1);        assert(ok.missing_moc_errors == 0 && ok.umbrella_violations == 0);            const std::vector<SourceUnit> legacy_broken = {            {"panel_window.hpp", true, false, true, 6},            {"panel_window.cpp", true, false, false, 0},            {"alarm_strip.hpp", true, false, true, 6},        };        const auto bad = hmi_build::audit_cmake_target(legacy_broken, 20, true, false);        assert(bad.missing_moc_errors == 1 && bad.umbrella_violations == 2);        assert(bad.estimated_kloc > ok.estimated_kloc * 10);            std::printf("AUTOMOC clean(hdr=%d inline=%d err=%d kloc=%d) "                    "broken(err=%d umbrella=%d kloc=%d)\n",                    ok.moc_header_jobs, ok.moc_inline_jobs,                    ok.missing_moc_errors, ok.estimated_kloc,                    bad.missing_moc_errors, bad.umbrella_violations,                    bad.estimated_kloc);        return 0;    }
  1. Asserts strict ISO C++20 (cxx_std >= 20, std_required == true, gnu_extensions == false) before scanning units.
  2. Routes .hpp Q_OBJECT classes to mocs_compilation.cpp and flags .cpp Q_OBJECT classes missing #include '*.moc'.

Inspecting Autogen Audit Metrics and System Call Output

Confirm that ./verify prints clean(hdr=2 inline=1 err=0 kloc=84) versus broken(err=1 umbrella=2 kloc=1680) and exits with status 0. Replacing two <QtWidgets> header includes with forward declarations across 6 client translation units drops modeled preprocessor work from 1680 kLOC to 84 kLOC—a 20x reduction—while catching the missing panel_window.moc include before link time.

Inspect the strace output below as well: the compiled C++20 binary flushes its formatted summary in one write(1, ...) system call and terminates via exit_group(0) without touching external environment files, making build-hygiene linters fast enough to run on every Git hook.

learner@ksa: ~/gl-q01/m01-l01
learner@ksa:~/gl-q01/m01-l01g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m01-l01./verifyAUTOMOC clean(hdr=2 inline=1 err=0 kloc=84) broken(err=1 umbrella=2 kloc=1680)learner@ksa:~/gl-q01/m01-l01
strace — learner@ksa: ~/gl-q01/m01-l01
learner@ksa:~/gl-q01/m01-l01strace -e trace=write,exit_group ./verifywrite(1, "AUTOMOC clean(hdr=2 inline=1 err"..., 79) = 79exit_group(0)                           = ?+++ exited with 0 +++

Build-Graph and Meta-Object Linker Pitfalls

Whenever ld fails with undefined reference to vtable for MyWidget or undefined reference to MyWidget::staticMetaObject, resist deleting your entire build directory blindly. Trace whether AUTOMOC saw the header in target sources, whether Q_OBJECT was added to an existing header without CMake re-scanning dependencies, or whether a .cpp-private Q_OBJECT omitted its trailing .moc include.

With strict -std=c++20, PRIVATE warning flags, imported Qt6::* targets, and forward-declared headers locked in place, our translation units are clean. In Lesson 1.2, we move from build-time compilation units to runtime C++20 move semantics and QObject parent-child ownership trees.

Adding Q_OBJECT to an Existing Header Without Triggering AUTOMOC Re-Scan:

  • Symptom: Adding Q_OBJECT to a previously plain class StatusCard : public QWidget compiles status_card.cpp.o cleanly, then fails at link time with undefined reference to vtable for StatusCard.
  • Root Cause: Declaring Q_OBJECT injects virtual declarations (metaObject(), qt_metacall()) whose out-of-line definitions live only inside moc_status_card.cpp; if the header was omitted from add_executable or build stamps were bypassed, moc never emitted those bodies.
  • Fix: List every .hpp file explicitly in add_executable / add_library alongside .cpp files and re-run cmake --build so <target>_autogen regenerates mocs_compilation.cpp.

Attaching -Werror with PUBLIC Visibility on Shared HMI Libraries:

  • Symptom: Upgrading GCC on a developer workstation breaks third-party consumers or generated test harnesses with -Werror=deprecated-declarations inside external headers.
  • Root Cause: Passing -Wall -Wextra -Werror under PUBLIC or INTERFACE in target_compile_options forces strict warning-as-error flags onto every downstream consumer target.
  • Fix: Scope strict warning flags (-Wall -Wextra -Werror -pedantic) as PRIVATE on each owned target and ensure external SDK paths enter as SYSTEM interface includes (which Qt6::* imported targets do automatically).

Guided Practice

Extend SourceUnit in verify.cpp with a boolean in_target_sources field and verify what happens when a header named telemetry_dialog_p.hpp (whose stem differs from telemetry_dialog.cpp) carries Q_OBJECT while in_target_sources == false. Why can AUTOMOC auto-discover telemetry_dialog.hpp from telemetry_dialog.cpp by stem matching yet miss telemetry_dialog_p.hpp unless the header is listed explicitly in add_executable?

Independent Practice

Audit an existing C++ or qmake .pro HMI directory layout and draft a clean CMakeLists.txt splitting pure C++20 protocol parsing (libprotocol, linking zero Qt libraries) from the GUI executable (ksa_hmi, linking libprotocol and Qt6::Widgets with PRIVATE visibility). Verify with Verify rules that libprotocol carries zero AUTOMOC overhead.

Verification Checks

quiz · 1 of 3

An engineer defines class PollWorker : public QObject { Q_OBJECT ... }; privately inside poller.cpp on a target with AUTOMOC ON, and linking fails with undefined reference to vtable for PollWorker. What fixes the build?

quiz · 2 of 3

Why should panel_window.hpp write class QPushButton; instead of #include <QtWidgets> when PanelWindow only stores QPushButton *m_armButton;?

quiz · 3 of 3

Which CMake target property trio enforces strict ISO C++20 without GNU extensions on ksa_hmi?

Key takeaways

  • Enabling CMAKE_AUTOMOC, CMAKE_AUTOUIC, and CMAKE_AUTORCC as target properties schedules moc, uic, and rcc in the CMake build graph automatically whenever headers, .ui forms, or .qrc manifests change.
  • Linking imported targets such as Qt6::Widgets via target_link_libraries propagates transitive include paths, compile definitions, and -fPIC flags without polluting unrelated targets like legacy .pro globals.
  • Declaring a private Q_OBJECT subclass directly inside worker.cpp requires #include "worker.moc" at the bottom of worker.cpp because mocs_compilation.cpp cannot see translation-unit-local types.
  • Forward-declaring pointer members (class QPushButton;) in widget headers instead of pulling the <QtWidgets> umbrella header isolates downstream translation units from massive preprocessor token fan-out.
Progress is saved on this device.

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure