C++ Standards
C++ Standards
Section titled “C++ Standards”Modern C++ that builds and behaves the same on macOS, Linux and Windows, with the sharp edges kept away from the people who call it from Swift, Kotlin, C# or Python. The C ABI section (§10) is the contract those wrappers depend on; the wrapping side itself lives in arch-07_cross_platform_shared_core_standards.md.
1. Language Baseline
Section titled “1. Language Baseline”- Baseline: C++20.
target_compile_features(<target> PUBLIC cxx_std_20)on every target; never setCMAKE_CXX_STANDARDglobally in a library that others consume. - Floor: C++17 where a platform toolchain lags (an older NDK, an embedded vendor compiler, a distro’s system GCC). A project that must honour the floor says so in its
READMEbuild matrix and in an ADR, and CI runs one lane on the floor compiler so the floor is real, not aspirational. - Extensions off.
CMAKE_CXX_EXTENSIONS OFF(-std=c++20, not-std=gnu++20)./permissive-on MSVC. Code that compiles on one compiler only is a bug. - C++20 features to rely on:
<span>,<concepts>,<ranges>(views only; avoid actions), designated initialisers,constexprcontainers and algorithms,<bit>,std::endian,[[likely]]/[[unlikely]], three-way comparison,std::jthread/std::stop_token. - Formatting:
fmt::formatfrom{fmt}behind a project alias (core::format) by default.std::formatneeds libc++ 17, libstdc++ 13 or MSVC 19.29, which is newer than the §2 minimums (Clang 16, GCC 12): a project may switch the alias tostd::formatonly when every compiler in its matrix ships it, and the matrix in itsREADMEsays so. - Not yet: C++20 modules (§7), coroutines in public APIs (the ABI of a coroutine frame is compiler-specific),
std::executionpolicies on libc++. These are allowed inside a single translation unit when the whole compiler matrix supports them and an ADR records the decision. - C++23:
std::expectedis the preferred result type (§9). On a C++20 toolchain usetl::expectedbehind a project alias so the switch is one header.
2. Toolchain Matrix
Section titled “2. Toolchain Matrix”Every project names its supported compilers in the README and CI builds on all of them. The minimums below are the floor for a C++20 baseline; raise them freely, never lower them silently.
| Compiler | Minimum | Platforms | Standard library |
|---|---|---|---|
| Clang / Apple Clang | 16 / Xcode 15 | macOS, iOS, Linux, Android (NDK r26+), WebAssembly (Emscripten 3.1.50+) | libc++ |
| GCC | 12 | Linux, MinGW | libstdc++ |
| MSVC | 19.36 (Visual Studio 2022 17.6) | Windows | MSVC STL |
Warning sets
Section titled “Warning sets”Warnings are declared once, on an INTERFACE target named after the project (${PROJECT_NAME}_warnings, alias ${PROJECT_NAME}::warnings — a fixed name would collide when two libraries built the same way meet in one build) that every target the project owns links. Copy templates/cpp/ProjectWarnings.cmake; it also carries the cxx_std_20 requirement (§1) and the coverage, clang-tidy and hardening switches the presets flip (§3). The sets it carries are:
| Compiler | Baseline set |
|---|---|
| Clang + GCC | -Wall -Wextra -Wpedantic -Wshadow -Wconversion -Wsign-conversion -Wnon-virtual-dtor -Wold-style-cast -Wcast-align -Woverloaded-virtual -Wnull-dereference -Wdouble-promotion -Wformat=2 -Wimplicit-fallthrough -Wunused |
| GCC extras | -Wmisleading-indentation -Wduplicated-cond -Wduplicated-branches -Wlogical-op -Wuseless-cast |
| Clang extras | -Wmost -Wextra-semi -Wunreachable-code -Wthread-safety (when annotations are used) |
| MSVC | /W4 /permissive- /Zc:__cplusplus /Zc:preprocessor /utf-8 /EHsc /w14242 /w14254 /w14263 /w14265 /w14287 /we4289 /w14296 /w14311 /w14545 /w14546 /w14547 /w14549 /w14555 /w14619 /w14640 /w14826 /w14905 /w14906 /w14928 |
Warnings as errors: on in CI, off by default
Section titled “Warnings as errors: on in CI, off by default”- Local builds show every warning and still link, so a developer on a newer compiler is not blocked by a diagnostic the project has not seen yet.
- CI builds fail on any warning: the
cipreset setsCMAKE_COMPILE_WARNING_AS_ERROR=ON(CMake 3.24+), which adds-Werror//WXto every target the project owns. Pass-Werrorexplicitly on toolchains older than 3.24. - Never hard-code
-WerrorinCMakeLists.txtwithout anoption()guard (<PROJECT>_WARNINGS_AS_ERRORS, defaultOFF). A consumer that adds your library withFetchContenton a compiler you did not test must not see their build break on a warning in your code. Same rule as Rust’s# and for the same reason. - Vendored code is exempt (§16): it is included as
SYSTEMand hasCOMPILE_WARNING_AS_ERROR OFF. - Enforced by
lint-checks/cpp/warnings-as-errors: PASS when a CI command enables-Werror,/WXorCOMPILE_WARNING_AS_ERROR, when the preset CI selects with--preset(or one it inherits) enables it, or whenCMakeLists.txt/cmake/*.cmakeenables it and a CI step runs the build; WARN when the build configuration enables it but no CI step builds the project or CI selects a different preset; FAIL otherwise.-Werror=<one-warning>does not count.
3. Build System
Section titled “3. Build System”-
CMake 3.25+ with Ninja. One
CMakeLists.txtper target directory;add_subdirectory, not one 2,000-line root file. -
Presets, not README incantations.
CMakePresets.json(version 6) is committed and is the only way CI configures, builds and tests. Copytemplates/cpp/CMakePresets.json.CMakeUserPresets.jsonis gitignored and holds personal overrides. Required presets:Preset Purpose devDebug, warnings on, warnings-as-errors off, compile_commands.jsonexportedciRelWithDebInfo, CMAKE_COMPILE_WARNING_AS_ERROR=ON, tests onci-asan-ubsanciplus-fsanitize=address,undefined(§13)ci-tsanciplus-fsanitize=thread— a separate build; TSan cannot share a binary with ASanreleaseRelease, LTO on where the toolchain supports it, tests off Workflow presets (
cmake --workflow --preset ci) chain configure, build and test so a CI job is one line. -
Target-based everything.
target_compile_features,target_compile_options,target_include_directories,target_link_librarieswithPUBLIC/PRIVATE/INTERFACE. Noinclude_directories(),add_definitions(),link_libraries()orCMAKE_CXX_FLAGSedits in project code; those leak into every consumer. -
Sources are listed, not globbed.
file(GLOB ...)hides a forgotten file until the build that misses it; list sources explicitly. -
Export
compile_commands.json(CMAKE_EXPORT_COMPILE_COMMANDS ONin thedevpreset): clang-tidy, clangd and include-what-you-use all read it. -
Install and package. A library target has
install(TARGETS ... EXPORT), a<Project>Config.cmakeand a version file, so a consumer canfind_package(Project 1.2 CONFIG REQUIRED). -
Dependencies (§15): a manifest plus a lock.
vcpkg.jsonwithbuiltin-baseline,conanfile.pywithconan.lock, orFetchContentpinned to a tag andGIT_TAG <full-sha>withFIND_PACKAGE_ARGSso a system package can satisfy it.
4. Code Style
Section titled “4. Code Style”- Formatter:
clang-format(version pinned in the README; the matrix’s Clang version)..clang-formatat the project root is the single style file; copytemplates/cpp/.clang-format. Commit only formatted code. CI runsclang-format --dry-run --Werror $(git ls-files '*.cpp' '*.hpp' ...)(orcmake --build --target format-check). Enforced bylint-checks/cpp/clang-format-config: PASS when a root.clang-formatexists with content, WARN when it is empty or lives only in a subdirectory, FAIL when missing. - Static analysis:
clang-tidywith the committedtemplates/cpp/.clang-tidy(bugprone, cert, cppcoreguidelines, modernize, performance, portability, readability, with the noisy checks turned off deliberately, not wholesale).--warnings-as-errors='*'in CI: thecipreset sets<PROJECT>_ENABLE_CLANG_TIDY=ON, whichProjectWarnings.cmaketurns intoCMAKE_CXX_CLANG_TIDYfor the targets the project owns, or a dedicatedclang-tidyjob runs overcompile_commands.json. Suppressions are// NOLINT(check-name): <reason>, never a bare// NOLINT. - Line length 100, 4-space indent, no tabs, braces on the same line (
Attach),east constis not used (const T&, left-aligned pointersT* p). - Includes are grouped and sorted by clang-format: the matching header first, then project headers, then third-party, then the standard library;
"project/..."for the project’s own headers,<...>for everything else. autowhere the type is obvious from the right-hand side or is an iterator/lambda; spell the type out when it is a domain type the reader needs to see.- No macros for constants, functions or control flow.
constexpr,inlinefunctions and templates cover every case except include guards, export annotations (§10) and platform#ifs (§14). [[nodiscard]]on every function whose return value is a status or a resource.
5. Naming Conventions
Section titled “5. Naming Conventions”| Entity | Style | Example |
|---|---|---|
| Namespaces | snake_case, one per project, nested by layer |
mesh_core::io |
| Types (class, struct, enum, alias, concept) | PascalCase |
MeshBuilder, VertexId |
| Functions, methods, variables, parameters | snake_case |
build_normals(), vertex_count |
| Private data members | snake_case_ with trailing underscore |
vertices_ |
| Constants and enumerators | kPascalCase |
kMaxVertices, Status::kNotFound |
| Template parameters | PascalCase |
template <typename Allocator> |
| Macros (rare, §4) | UPPER_SNAKE_CASE with project prefix |
MESH_CORE_EXPORT |
| Files | snake_case.hpp / snake_case.cpp; tests snake_case_test.cpp |
mesh_builder.hpp |
| C ABI symbols (§10) | <prefix>_<noun>_<verb> |
dust3d_mesh_create |
Enumerations are enum class; never enum. Booleans read as predicates (is_closed, has_normals). Getters have no get_ prefix (size(), not get_size()).
6. Project Structure
Section titled “6. Project Structure”include/└── mesh_core/ # Public headers only; one directory per library ├── mesh.hpp ├── export.hpp # MESH_CORE_EXPORT visibility macro (§10) └── expected.hpp # std::expected / tl::expected alias (§9)src/├── mesh/ # Implementation, private headers next to .cpp│ ├── mesh.cpp│ └── mesh_internal.hpp└── platform/ # The only directory allowed to #if on the OS (§14) ├── file_posix.cpp └── file_windows.cppbindings/└── c/ # extern "C" facade (§10): mesh_core_c.h + .cpptests/├── unit/├── conformance/ # Golden vectors shared with the wrappers (arch-07 §2)└── fuzz/cmake/├── ProjectWarnings.cmake└── MeshCoreConfig.cmake.inthird_party/ # Vendored verbatim (§16), own .clang-format with DisableFormatCMakeLists.txtCMakePresets.json.clang-format.clang-tidyDomain and application layers (core-standards) are plain C++ with no OS, UI or binding includes; src/platform/ and bindings/ are the infrastructure layer.
7. Header Hygiene and Modules
Section titled “7. Header Hygiene and Modules”- Self-contained headers. Every header compiles on its own (
#includewhat you use; CI can runinclude-what-you-useor aheader-checktarget that compiles each public header as its own TU). #pragma oncein every header; all three compilers honour it and it cannot be mistyped the way a guard macro can.- No
using namespaceand nousing std::x;at namespace scope in a header. Inside a function body is fine. - Forward-declare in headers; include the full definition in the
.cpp. Public headers include only other public headers and the standard library — a private header or third-party header ininclude/leaks the dependency to every consumer. - Templates and
inlinein headers only when they must be. A public header that pulls<regex>or<iostream>into every consumer is a compile-time regression for all of them. Use PIMPL (std::unique_ptr<Impl>with the destructor defined in the.cpp) for classes that cross a shared-library boundary or carry heavy private dependencies. - ABI-stable public API: no
std::string,std::vectoror other STL types in the signature of a function exported from a shared library that another compiler or standard library may consume; that is the C ABI’s job (§10). Within one build tree (static libraries, same compiler) STL types in headers are fine. - C++20 modules are allowed only when every compiler in the matrix (§2) and CMake 3.28+ with Ninja 1.11+ are in place, the module is internal to one build tree, and an ADR records the decision. Public interfaces stay headers until the ecosystem (package managers, clang-tidy, IDEs) is uniform; never export a module across the C ABI or to a wrapper language.
8. Ownership, Lifetime and RAII
Section titled “8. Ownership, Lifetime and RAII”- No naked
new/delete.std::make_unique,std::make_shared, containers andstd::optionalown everything. A raw pointer is always non-owning and may be null unless the comment says otherwise;gsl::not_null/std::reference_wrapperor a reference expresses “never null”. std::unique_ptris the default owner.std::shared_ptrneeds a sentence in the comment saying who the co-owners are. Nostd::shared_ptr<T>parameters where aT&orconst T&would do.- Borrow with views:
std::span<const T>andstd::string_viewfor read-only, non-owning parameters. Never store astring_view/spanin a member unless the type’s documentation names the owner whose lifetime it is tied to. - Rule of zero. A class either manages one resource and declares all five special members (or deletes copy and defaults move), or it declares none. Destructors and move operations are
noexcept. - No raw owning arrays, no
malloc/freein C++ code except inside a C-ABI allocator shim (§10) that documents the pairing. - Resource handles are types.
FileHandle,GpuBuffer, notint fdorvoid*passed around. - Const-correctness: member functions that do not mutate are
const; pass byconst&for anything larger than two words, by value for sinks (std::string namethenstd::move).
9. Error Handling
Section titled “9. Error Handling”- Expected failures are values. Public functions that can fail return
expected<T, Error>(alias ininclude/<project>/expected.hpptostd::expectedon C++23,tl::expectedon C++20).Erroris a small struct: a projectErrorCodeenum class plus a bounded message. Callersand_then/transform/or_elseor match explicitly. - Status enums at boundaries. The C ABI (§10), callbacks into other languages and any
extern "C"signature return a<prefix>_statusinteger enum:0is success, every other value is a documented, stable, never-reused code. TheErrorCode→ status mapping is one table in the facade. - Exceptions are for bugs and resource exhaustion, inside the core only:
std::bad_alloc, a violated precondition in a constructor, a corrupted invariant. They are never part of a function’s documented contract, never caught to implement control flow, and never cross the C ABI, a thread boundary or a callback into another runtime (§10.4). noexcepton destructors, move constructors/assignments, swap and any function the C ABI calls directly.- No silent swallowing.
catch (...) {}is banned. The onlycatch (...)lives at the C-ABI boundary and converts to a status code plus a diagnostic (§10.4). - Assertions:
assert()for internal invariants (compiled out in release); a projectPROJECT_EXPECTS(cond)macro or[[assume]]-freeif (!cond) return Error{...}for preconditions on public input. A violated public-input precondition is an error return, not a crash. - Errors carry context, not stack traces. Format diagnostics with
std::format/fmt::formatinto a bounded buffer; log at the boundary, once.
10. The C ABI Boundary
Section titled “10. The C ABI Boundary”The C facade (bindings/c/) is the only thing Swift, Kotlin/JNI, C#, Python and Rust see. It has stricter rules than the rest of the codebase because a mistake there is a host-process crash with no C++ backtrace, in an app that ships through an app store. The wrapper side — conformance vectors through the FFI, export smoke tests, generated-binding drift gates — is arch-07 §3; this section is the C++ side of the same contract.
10.1 Shape of the API
Section titled “10.1 Shape of the API”extern "C", C99-compatible header.bindings/c/<project>_c.hcompiles as C and as C++ (#ifdef __cplusplus extern "C" {). It includes only<stdint.h>,<stddef.h>,<stdbool.h>and the project’s export header.- Opaque handles.
typedef struct <prefix>_mesh* <prefix>_mesh_handle;— the struct is never defined in the header. No C++ class, no STL type, no reference, noboolin a struct layout (useuint8_t/int32_t), noenumas a parameter, return or field type (a status or flag type istypedef int32_t <prefix>_statuswith its values named by an anonymousenum— C99 has no fixed underlying type forenum, and C23’senum e : int32_tdoes not compile under the header’s C99 floor), no bitfields. - Fixed-width scalars only:
int32_t,uint64_t,double,size_tfor byte counts,const char*UTF-8 NUL-terminated for strings. Neverlong,wchar_t,size_tin a struct that is persisted, orstd::size_tin the header. - Naming:
<prefix>_<noun>_<verb>(dust3d_mesh_create,dust3d_mesh_destroy,dust3d_mesh_vertex_count). The prefix is the project’s and never changes. - Symbol visibility:
-fvisibility=hidden(CMAKE_CXX_VISIBILITY_PRESET hidden,CMAKE_VISIBILITY_INLINES_HIDDEN ON) on every target; only functions annotated<PREFIX>_EXPORT(__attribute__((visibility("default")))/__declspec(dllexport)) are visible. Nothing insrc/is exported. - ABI version:
<prefix>_abi_version()returns a monotonically increasinguint32_t, and the header defines<PREFIX>_ABI_VERSION. A wrapper checks them at load time. Any change to a struct layout, enum value or function signature bumps it; additive changes (new functions) do not.
10.2 Ownership and lifetime rules
Section titled “10.2 Ownership and lifetime rules”- Every
createhas onedestroy, and only thatdestroyfrees it. A handle created by<prefix>_mesh_createis released by<prefix>_mesh_destroy, never byfree(), never by another type’s destroy. The header documents the pair next to eachcreate. - No allocator ownership crosses the boundary. Memory the library allocates is freed by the library; memory the caller allocates is freed by the caller. If the library must return a buffer it does not own a handle for, it provides
<prefix>_buffer_free(ptr)— or, preferably, takes a caller-provided buffer and returns the required size when it is too small (required_lenout-parameter, statuskBufferTooSmall). - Borrowed buffers expire with their owner. A pointer returned by an accessor (
const float* <prefix>_mesh_vertices(handle, size_t* count)) is valid only until the next mutating call on that handle or its destruction, whichever is first. The header states this on every accessor. A wrapper that needs to keep the data copies it. - Strings in are borrowed for the call only. The library never stores a
const char*the caller passed; it copies into astd::stringif it needs it later. - Callbacks carry a
void* user_dataand are invoked only during the API call that registered them unless the header says otherwise; the library never calls back afterdestroyreturns. - Null handles are tolerated. Every accessor on a null handle returns the zero value (
0,nullptr,kInvalidHandlestatus) and never dereferences.destroy(nullptr)is a no-op, likefree(NULL). A wrapper that fails half-way through construction can tear down unconditionally. - Threading is documented per handle. By default a handle is not thread-safe and the library serialises engine calls behind one mutex when the underlying engine (OpenGL context, a global allocator, a third-party library with static state) requires it. The header says which: “all calls are serialised by the library” or “a handle may be used from one thread at a time”. Never “probably fine”.
10.3 Status codes and diagnostics
Section titled “10.3 Status codes and diagnostics”/* The status type is a fixed-width integer, not an enum: C99 has no way to fix an enum's underlying type (C23 does, but this header compiles as C99). The anonymous enum only names the values. */typedef int32_t dust3d_status;enum { DUST3D_OK = 0, DUST3D_ERR_INVALID_HANDLE = 1, DUST3D_ERR_INVALID_ARGUMENT = 2, DUST3D_ERR_BUFFER_TOO_SMALL = 3, DUST3D_ERR_PARSE = 4, DUST3D_ERR_OUT_OF_MEMORY = 5, DUST3D_ERR_INTERNAL = 99 /* a C++ exception reached the boundary; see dust3d_last_error */};
/* Copies the last diagnostic for the calling thread into buf (always NUL-terminated, truncated to buf_len - 1); returns the length that would have been needed. */DUST3D_EXPORT size_t dust3d_last_error(char* buf, size_t buf_len);- Codes are stable and never reused: a removed code stays in the enum as
DUST3D_ERR_RESERVED_N. - The diagnostic lives in a thread-local, fixed-size buffer (
char[512]) written withstd::snprintf, so reporting an error can never itself allocate or throw. The wrapper reads it immediately after a non-zero status.
10.4 Catch everything at the boundary
Section titled “10.4 Catch everything at the boundary”Every extern "C" function body is a single try whose handlers map to a status; nothing else is allowed to execute outside it.
namespace {thread_local char g_last_error[512] = "";
void set_last_error(const char* what) noexcept { std::snprintf(g_last_error, sizeof g_last_error, "%s", what ? what : "unknown error");}
template <typename Fn>dust3d_status guarded(Fn&& fn) noexcept { try { return fn(); } catch (const std::bad_alloc&) { set_last_error("out of memory"); return DUST3D_ERR_OUT_OF_MEMORY; } catch (const std::exception& e) { set_last_error(e.what()); return DUST3D_ERR_INTERNAL; } catch (...) { set_last_error("non-standard exception"); return DUST3D_ERR_INTERNAL; }}} // namespace
extern "C" DUST3D_EXPORT dust3d_status dust3d_mesh_parse(const uint8_t* bytes, size_t len, dust3d_mesh_handle* out) { return guarded([&]() -> dust3d_status { if (out == nullptr) return DUST3D_ERR_INVALID_ARGUMENT; *out = nullptr; if (bytes == nullptr && len != 0) return DUST3D_ERR_INVALID_ARGUMENT; auto mesh = dust3d::parse(std::span<const uint8_t>{bytes, len}); // expected<Mesh, Error> if (!mesh) { set_last_error(mesh.error().message.c_str()); return to_status(mesh.error().code); } *out = reinterpret_cast<dust3d_mesh_handle>(new dust3d::Mesh(std::move(*mesh))); return DUST3D_OK; });}
extern "C" DUST3D_EXPORT void dust3d_mesh_destroy(dust3d_mesh_handle handle) { delete reinterpret_cast<dust3d::Mesh*>(handle); // delete nullptr is a no-op}-fno-exceptionsis not the answer: the core may still throwbad_alloc, and a third-party library may throw anything. The boundary converts; the lint keeps it honest.std::terminateis reachable only through anoexceptviolation, which theguardedwrapper makes impossible for the exported functions.- The wrapper languages’ rules for the other side — never store a borrowed pointer past the owner, check the ABI version, run the conformance vectors through the FFI — are in arch-07 §3. The two documents describe one contract.
11. Concurrency
Section titled “11. Concurrency”std::jthread+std::stop_token, neverstd::threadwithout a join plan and neverdetach().- Shared state is protected or atomic. A data race is undefined behaviour, not a flaky test.
std::mutex/std::scoped_lock,std::atomic<T>with the weakest ordering the comment can justify, or message passing.volatileis not a synchronisation primitive. - Clang thread-safety annotations (
GUARDED_BY,REQUIRES) on every mutex-protected member when building with Clang; they turn locking mistakes into compile errors. - No blocking in callbacks that arrive from another runtime (a Swift completion handler, a JNI callback); hand off to the engine’s own queue.
- The TSan lane (§13) is mandatory for any target that creates a thread.
12. Testing
Section titled “12. Testing”- Framework: GoogleTest (or Catch2 v3) registered with CTest via
gtest_discover_tests/catch_discover_tests.ctest --test-dir build --output-on-failureis the only test command CI runs; a test preset wraps it. - Layout:
tests/unit/<module>_test.cppmirrorssrc/;tests/conformance/holds the golden vectors shared with every wrapper (arch-07 §2);tests/fuzz/holds libFuzzer targets for every parser and decoder (-fsanitize=fuzzer, run with a time budget in CI, corpus committed). - Coverage: 95% minimum per target, 100% for domain logic (core-standards).
--coveragewithgcovr(GCC) or-fprofile-instr-generate -fcoverage-mappingwithllvm-cov(Clang); thecipreset turns it on and the gate reads the report. The C facade is covered through the conformance suite, which calls theextern "C"API, not the C++ classes behind it. - Death tests for every precondition that aborts in debug; no test depends on undefined behaviour (the sanitizer lanes run the same test binaries).
- Determinism: no wall-clock, no network, no filesystem outside a per-test temp dir created by the fixture. Random inputs use a seeded
std::mt19937_64and print the seed on failure. - Cross-platform tests: path handling, line endings and encoding (§14) have tests that run on all three OSes, not just the one the author uses.
13. Sanitizer Lanes
Section titled “13. Sanitizer Lanes”Sanitizers find the bugs the warnings cannot. They run the test suite, not just the build, on every PR.
| Lane | Preset | Flags | Platforms |
|---|---|---|---|
| ASan + UBSan | ci-asan-ubsan |
-fsanitize=address,undefined -fno-omit-frame-pointer -fno-sanitize-recover=all |
Linux (Clang or GCC), macOS (Clang); MSVC /fsanitize=address for ASan only |
| TSan | ci-tsan |
-fsanitize=thread -fno-omit-frame-pointer |
Linux Clang; required when any target spawns a thread |
| MSan (optional) | ci-msan |
-fsanitize=memory -fsanitize-memory-track-origins |
Linux Clang only; requires an instrumented libc++ |
- Environment in CI:
ASAN_OPTIONS=detect_leaks=1:strict_string_checks=1:check_initialization_order=1(detect_leaks=0on macOS, where LSan is unavailable),UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1,TSAN_OPTIONS=halt_on_error=1 second_deadlock_stack=1. - ASan and TSan are separate builds; they cannot be combined in one binary.
- Sanitizer lanes build with the §17 hardening flags off:
_FORTIFY_SOURCEand AddressSanitizer interfere, and the lane measures the sanitizer. On MSVC,/fsanitize=addressis incompatible with/RTC1and incremental linking, so theci-msvc-asanpreset replaces the default Debug flags (/MDd /Zi /Ob0 /Od,/INCREMENTAL:NO). - Hardened standard library in Debug and sanitizer builds:
-D_GLIBCXX_ASSERTIONS(libstdc++) or-D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_EXTENSIVE(libc++ 18+) sooperator[]is bounds-checked where the sanitizer cannot see. - A finding in a sanitizer lane is a bug, not a flake; suppressions (
-fsanitize-blacklist,ASAN_OPTIONS=suppressions=) name a third-party library and an issue number, never project code. - Enforced by
lint-checks/cpp/sanitizer-lane: PASS when a CI step passes-fsanitize=//fsanitize=, or selects a CMake preset that (itself or throughinherits) sets it, and CI runs the tests (ctest, acmake --workflowwhose preset has a test step,make test); WARN when the sanitizer build never runs the tests, when CI selects a sanitizer-named preset that sets no flag, or when a sanitizer preset or option exists but no CI lane runs it; FAIL when CI has no sanitizer lane.
14. Cross-Platform Rules
Section titled “14. Cross-Platform Rules”Files, encoding, line endings
Section titled “Files, encoding, line endings”- Source files are UTF-8 without BOM.
.editorconfig(charset = utf-8,end_of_line = lf,insert_final_newline = true,indent_style = space,indent_size = 4) and.gitattributeswith* text=auto eol=lfplus explicit-textfor binaries (*.png,*.bin,*.obj, test fixtures), so a Windows checkout cannot turn a fixture into CRLF. - Compilers read UTF-8:
/utf-8on MSVC (source and execution charset),-finput-charset=UTF-8is already the default on GCC/Clang. Without/utf-8a string literal with a non-ASCII character is silently re-encoded on Windows. - Text data is UTF-8 end to end.
std::stringholds UTF-8;std::u8stringonly where a type-level guarantee helps; nowchar_t/std::wstringin portable APIs (it is 16-bit on Windows and 32-bit elsewhere). Convert at the Win32 call (MultiByteToWideChar) insrc/platform/, nowhere else. - Line endings in data: parsers accept
\nand\r\n; writers emit\nunless the format mandates otherwise. Tests contain both.
Paths and the filesystem
Section titled “Paths and the filesystem”std::filesystem::patheverywhere; build paths with/, never string concatenation.path::u8string()when a UTF-8std::stringis needed;path::native()only insidesrc/platform/.- Case-sensitive filesystems are the norm (Linux, iOS devices);
#includepaths and asset names must match case exactly. CI runs on Linux so a macOS-only mismatch is caught. - No path longer than 260 characters assumed to work on Windows without the long-path manifest; no reserved names (
aux.cpp,con.hpp,nul).
Integers, layout and the ABI
Section titled “Integers, layout and the ABI”- Fixed-width types (
<cstdint>) in anything serialised, persisted or crossing the C ABI.intandlongdiffer between MSVC and everyone else (longis 32-bit on Windows). std::endian::nativechecks and explicit byte-swap (std::byteswap, C++23, or a project helper) in binary readers; neverreinterpret_casta struct onto a byte buffer (alignment and padding are compiler-defined). Usestd::memcpyorstd::bit_cast.- Struct layouts that cross the ABI are
static_assert(sizeof(T) == N)andstatic_assert(std::is_standard_layout_v<T>).
Platform code
Section titled “Platform code”- One place:
src/platform/is the only directory where#if defined(_WIN32),__APPLE__,__linux__,__ANDROID__,__EMSCRIPTEN__appear. Everything else calls a platform-neutral interface. Prefer separate*_posix.cpp/*_windows.cppfiles selected in CMake over#ifladders inside one file. windows.hnever appears in a public header. Where it is included:#define WIN32_LEAN_AND_MEANand#define NOMINMAXfirst.std::min/std::maxare written(std::min)(a, b)only in files that must includewindows.h; elsewhereNOMINMAXmakes the parentheses unnecessary.- Symbol export is
__declspec(dllexport)/dllimporton Windows andvisibility("default")elsewhere, behind one generated or hand-writtenexport.hpp(GenerateExportHeaderdoes it). - No
#pragma comment(lib, ...), no__declspecin portable code, no#pragma packwithout a matchingstatic_assert. - Shell and scripts: build helpers are CMake scripts (
cmake -P) or Python, not bash — Windows CI has neither bash nor coreutils by default.
15. Dependencies and Supply Chain
Section titled “15. Dependencies and Supply Chain”- Manifest + lock, always:
vcpkg.jsonwithbuiltin-baseline(andvcpkg-configuration.jsonfor registries), orconanfile.py+conan.lock, orFetchContentwithGIT_TAGset to a full commit SHA (a tag can move).make deps-update(arch-02) is the only way the lock changes. - Audit: CI runs
osv-scanner --lockfile vcpkg.json(or the Conan equivalent) and fails on known CVEs (sec-01 §5). Header-only libraries count too. - Licenses: an allow-list in
THIRD_PARTY_LICENSES.md(orvcpkglicensefield checks); a new copyleft dependency fails review until consciously added. Every vendored library’s license file ships with it. - System packages are satisfied with
find_package(... CONFIG)first andFetchContentas fallback (FIND_PACKAGE_ARGS), so distro packagers and Homebrew users are not forced to rebuild the world. - No Git submodules for dependencies in new projects; they bypass the lock and the audit.
16. Vendored Code Preservation
Section titled “16. Vendored Code Preservation”Inherited and vendored code (a third-party engine, a historical codebase a product grew from, a header-only library copied in) is kept verbatim so upstream diffs stay reviewable and upstream fixes still apply.
- Lives in
third_party/<name>/with anUPSTREAM.mdnaming the origin URL, version or commit, license, and the list of local modifications (file, reason, issue). An empty modifications list is the goal. - No mass reformat, ever.
third_party/.clang-formatcontainsDisableFormat: trueandSortIncludes: Never;.clang-tidyexcludes it viaHeaderFilterRegex; the pre-commit hook and the CI format check skip it. A reformatting commit destroys the ability togit diffagainst upstream and to apply upstream patches, and it buries any real change in noise. - No drive-by modernisation. Do not fix warnings, rename identifiers, replace
NULLwithnullptror convert toenum classin vendored code. Warnings are silenced at the build level:target_include_directories(... SYSTEM ...)andset_target_properties(<vendored> PROPERTIES COMPILE_WARNING_AS_ERROR OFF); a vendored target may carry its own, narrower warning set. - Changes are patches. A necessary local fix lands as
third_party/<name>/patches/NNNN-<slug>.patchapplied at configure time (or recorded inUPSTREAM.mdwhen applied in place), with an upstream issue or PR link. Prefer wrapping (an adapter insrc/) over editing. - Coverage and lint treat it as
inherited: declarelayer: inheritedincoverage.scopes(proc-05 § 6) with the upstream suite as the stated reason, and list the directory inlint.excludefor the banned-function scans (no-secretsstill runs — a vendored secret is still a secret). - Updating replaces the directory wholesale from the new upstream version, re-applies the patches, and bumps
UPSTREAM.mdin onechore(third_party): bump <name> to <version>commit. - Ownership of code you inherited (not from a public upstream) follows the same rules until the team decides to adopt it: adoption is an ADR plus a single reformatting commit, after which the directory moves out of
third_party/and the normal standards apply.
17. Security
Section titled “17. Security”- Banned functions (sec-01 §4):
gets,strcpy,strcat,sprintf,vsprintf,scanf("%s")without a width,strtok,atoi/atol/atofon untrusted input (no error reporting — usestd::from_chars),system(),popen(),tmpnam,rand()for anything security-relevant,alloca, rawmemcpyinto a buffer whose size is not checked on the same line.clang-tidy’scert-*andbugprone-*groups flag most of these; the rest is review. - Bounds:
std::span,.at()in non-hot paths, hardened library mode in Debug/sanitizer builds (§13),-fsanitize=boundsunder UBSan. Every length that arrives across the C ABI is validated against the buffer it describes before use. - Integer safety:
-Wconversion -Wsign-conversionin the warning set; checked arithmetic (__builtin_add_overflow,std::add_satin C++26, or a project helper) on sizes computed from untrusted input before any allocation. - Hardening flags in
releaseandci:-D_FORTIFY_SOURCE=3 -fstack-protector-strong -fstack-clash-protection -fPIE -pie -Wl,-z,relro,-z,now -Wl,-z,noexecstack(GCC/Clang, Linux),-fcf-protection=fullon x86-64;/GS /guard:cf /DYNAMICBASE /NXCOMPAT /HIGHENTROPYVA /SDLon MSVC. On macOS, hardened runtime and library validation at codesign time. - Randomness:
std::random_deviceis acceptable on the mainstream platforms for seeding; secrets and tokens come from the OS CSPRNG (getrandom(2),SecRandomCopyBytes,BCryptGenRandom) or a vetted crypto library (libsodium, OpenSSL 3), never<random>engines alone. - Parsing untrusted input gets a fuzz target (§12) and runs under ASan/UBSan in CI before it ships.
- Secrets are never compiled in;
#define API_KEYandconstexpr char kToken[]are hardcoded-credential P0 findings. Configuration arrives through the platform’s secure store or environment at runtime. - See sec-01_security_standards.md for the severity model and the cross-language tables.
18. Documentation
Section titled “18. Documentation”- Public headers carry Doxygen comments (
///or/** */) on every exported type and function: one-line summary, parameters (ownership and lifetime for pointers — §10.2), return value, error codes, thread-safety.doxygen -gconfig committed;WARN_AS_ERROR = YESin the docs lane so an undocumented export fails. - The C header is the wrapper authors’ manual. Every
extern "C"declaration states: who allocates, who frees, how long a returned pointer lives, which status codes it can return, and whether it may be called concurrently. An undocumented rule does not exist. - README build matrix: the compiler/OS table from §2 as the project actually tests it, the preset names, and the one command that runs everything (
cmake --workflow --preset ci). - ADRs (proc-01) for: raising or lowering the language baseline or compiler floor, adopting modules or coroutines, changing the ABI version policy, adopting inherited code (§16).
19. Enforcement
Section titled “19. Enforcement”| Rule | Mechanism |
|---|---|
Root .clang-format committed (§4) |
lint-checks/cpp/clang-format-config |
| Warnings as errors in CI (§2) | lint-checks/cpp/warnings-as-errors |
| Sanitizer lane in CI (§13) | lint-checks/cpp/sanitizer-lane |
| Formatting, naming, include order (§4, §5) | clang-format --dry-run --Werror, clang-tidy readability-identifier-naming |
No new/delete, no C arrays, no catch (...) outside the facade (§8, §9) |
clang-tidy cppcoreguidelines-owning-memory, cppcoreguidelines-avoid-c-arrays, bugprone-empty-catch + review |
| Banned functions (§17) | clang-tidy cert-*, bugprone-*, review |
| C ABI contract (§10) | Conformance suite through the FFI, export smoke tests, ABI-version check (arch-07 §3) |
| Vendored code untouched (§16) | third_party/.clang-format with DisableFormat: true; UPSTREAM.md reviewed on every change under third_party/ |