r/cpp • • Aug 07 '25

I wrote a comprehensive guide to modern CMake using a real 80-file game engine project (not another hello-world tutorial)

After struggling with CMake on my game engine project for months, I decided to document everything I learned about building professional C++ build systems.

Most CMake tutorials show you toy examples with 2-3 files. This guide uses a complex project - my ColumbaEngine, an open source c++ game engine ([github](https://github.com/Gallasko/ColumbaEngine)) with 80+ source files, cross-platform support (Windows/Linux/Web), complex dependencies (SDL2, OpenGL, FreeType), and professional distribution.

Part 1 covers the compilation side:

  • Modern target-based CMake (no more global variables!)
  • Dependency management strategies (vendoring vs package managers vs FetchContent)
  • Cross-platform builds including Emscripten for web
  • Precompiled headers that cut build times by 60%
  • Generator expressions and proper PUBLIC/PRIVATE scoping
  • Testing infrastructure with GoogleTest

The examples are all from production code that actually works, not contrived demos.

https://medium.com/@pigeoncodeur/cmake-for-complex-projects-part-1-building-a-c-game-engine-from-scratch-for-desktop-and-774426c5f1f7

Part 2 (coming soon) will cover installation, packaging, and distribution - the stuff most tutorials skip but is crucial for real projects.

Hope this helps other developers dealing with complex C++ builds! Happy to answer questions about specific CMake pain points.

475 Upvotes

81 comments sorted by

View all comments

41

u/not_a_novel_account cmake dev Aug 07 '25

Mostly good. Fast stuff because I use reddit too much at work already:

  • Don't mess with global CMAKE_ variables. You mention this at the end but violate it at the beginning. It's not up to you what C++ version I build your code with, etc. Maybe I need all the code compiled with C++23, maybe C++26, maybe C++41. Your project doesn't know, so don't make the assumption. Leave globals alone, I setup them up just how I like them. If you need guaranteed features use target_compile_features().
  • Randomly putting a single source file in add_executable() is weird and can possibly lead to some unexpected behavior when done with add_library. It's not wrong exactly, just strange, put them all in target_sources().
  • Don't use target_include_directories(), prefer FILE_SET, the obscure generator expressions and complex install commands that target_include_directories() will necessitate are precisely why. This is also why CMake 3.22 is a little too old to be considered "modern".
  • Using GenEx for elements of the build known at configure time, which are able to be evaluated at configure time, is pointless. The examples for using GenEx purely as a platform check, or purely as a compiler check, are not recommended. Use GenEx only as a last resort, when elements of the conditional cannot be known at configure time. Otherwise prefer plain-ol if().
  • Unguarded use of vendored dependencies or FetchContent, etc, are hostile to packagers, and require downstream patching to be removed. These should always be behind default-off options. The default build configuration should assume that find_package() works because the packager producing the build has correctly configured the build environment. Modern CMake is find_package(), FetchContent is a mechanism for super-builds, not individual projects.

Generally go check out the Beman Standard for CMake. Their best practices are the upstream recommended best practices and they have plenty of projects exercising them.

47

u/zhaverzky Aug 07 '25

This is my primary issue with CMake, every single time someone posts advice on its use here or anywhere someone else who sounds just as authoritative says "don't do x, it's outdated/arcane/being used improperly here, do y instead" and we get deeper into the maelstrom of conflicting CMake info. Like what does "FetchContent is a mechanism for super-builds, not individual projects." even mean? I've never heard the term "super-build" before and I've been doing this for a while

15

u/throw_cpp_account Aug 07 '25

Especially when a 3-year-old release is already "too old to be considered modern"

6

u/joemaniaci Aug 07 '25

I know right?

I've been learning cmake the last month or two. Learned quickly to not use things like include_directories when an equivalent target_-like function such as target_include_directories is available, and now even that is out of date?

→ More replies (1)

17

u/not_a_novel_account cmake dev Aug 07 '25 edited Aug 07 '25

I'm primarily the one responsible for all the bad information as I own the upstream CMake tutorial from which most "bad" secondary sources flow (not to say other's tutorials are bad, everyone is trying their best to help).

Take that as authoritative or not, but I feel a certain obligation to point out corrections I should have gotten into the upstream tutorial a million years ago, at least when it pops up in front of me.

A superbuild is a build that describes incorporating a full graph of dependencies inside a single project. Concretely, you have some repo with no source code, only dependencies, and in the CMakeLists.txt for that otherwise empty project you describe where to grab all the dependencies, how to configure and build them, and where to install them.

Old blog post about it: https://www.kitware.com/cmake-superbuilds-git-submodules/

8

u/Xavier_OM Aug 07 '25

Care to elaborate about add_executable/add_library vs using target_sources later on ?

4

u/not_a_novel_account cmake dev Aug 07 '25 edited Aug 08 '25

With add_executable(), you almost always intend for all sources to be private sources (the cases where that's not true are exotic), which is the behavior you get from including the sources directly in the add_executable() or add_library() command.

With add_library(), there are various valid reasons you might want a public or an interface source (still uncommon, but not as bizarre as with executables). For this reason it's better to be explicit via target_sources(). If you know all these rules and have intentionally made a decision about the scope of your source files, it's fine either way.

Personally I think it looks weird to have a single source file argument to add_executable() and the rest in target_sources(), but that's a me problem.

1

u/Xavier_OM Aug 07 '25

Thanks, I can see the point here.

8

u/PigeonCodeur Aug 07 '25

Thank you so much for the detailed feedback! Really appreciate you taking the time to share these insights - this is exactly the kind of expert perspective that makes the article better.

You're absolutely right on several points, and I can see I've fallen into some common patterns that aren't actually best practice:

On global CMAKE_ variables: That's a great point about C++ standards, though I saw another comment that made a good distinction - when you're distributing as an installed package, you actually do want the library to specify the C++ version (after checking if it's already been set), since otherwise it defaults to the minimum supported version rather than taking advantage of newer features available on the platform. So there's a nuance between "project being consumed via add_subdirectory" vs "installed package" that I should clarify in the article.

On FILE_SET vs target_include_directories(): This is a great point about more modern approaches. The project started about 4 years ago and the CMake has evolved along with it, so I'm still using some older patterns for backward compatibility. But now that I'm preparing to publish the engine more widely, it's probably time to embrace the newer CMake features and update the minimum version requirement. The generator expression complexity you mention is exactly the kind of thing that made the installation section feel overly complicated. Will definitely research this approach.

On GenEx usage: This is a really good distinction - I think I got carried away showing off generator expressions when simple if() statements would be clearer and more appropriate for configure-time decisions. The "use GenEx as last resort" guideline is helpful.

On dependency defaults: The point about being hostile to packagers is spot-on. Making vendoring/FetchContent the default definitely creates problems downstream. Flipping to find_package() as default with opt-in fallbacks makes much more sense.

I'll check out the Beman Standard - hadn't come across that resource before but it sounds like a great ressource.

Thanks again for the corrections. It's feedback like this that helps the community learn the right patterns instead of perpetuating cargo-cult CMake. Mind if I reference some of these points in a follow-up article addressing these improvements?

6

u/not_a_novel_account cmake dev Aug 07 '25

since otherwise it defaults to the minimum supported version rather than taking advantage of newer features available on the platform

What language version is used is entirely up to the packager, not the author of the code. If the code is incompatible with a given language version, then the code will not build, and the packager will discover that in short order.

"Taking advantage of newer features" is not an advantage, especially where it has ABI implications. A infrastructure library will often have multiple ABIs, some for newer language versions, for example which enable C++ ranges and other such modern features, and some for older language versions, which may be built around iterators.

Avoiding incompatible symbol collision across many usages of the library in different contexts will necessitate a consistent language version, which may be older or newer depending on the packager's intended usage.

The point is to understand where the responsibility lies for making the decision, with the packager or with the developer. In this case the decision lies with the packager.


Feel free to use whatever you find helpful from my comments.

3

u/PigeonCodeur Aug 07 '25

Ah, that makes perfect sense - thank you for the clarification! You're absolutely right that I was thinking about this backwards.

The ABI implications you mention are exactly the kind of thing I hadn't considered. Having multiple ABIs for different language versions, and avoiding symbol collision across different usages - that's a level of library design complexity that I clearly need to understand better.

I can see now that my perspective was too focused on "my project in isolation" rather than "my project as part of a larger ecosystem managed by packagers." The packager knows the target environment and compatibility requirements way better than I do as the library author.

This is really helpful context for understanding the broader responsibility boundaries in the CMake/packaging ecosystem. I was definitely approaching it from the wrong angle.

2

u/azswcowboy Aug 07 '25

wrt the c++ version topic, these days in libraries I put a macro check on the c++ version or feature test macro in a header that’s always included. If the test fails you get a nice error saying you need c++23 or whatever. These are often header only so you can see someone just dropping the header into their own project without any of the supplied cmake logic.

4

u/Plazmatic Aug 07 '25

Maybe I need all the code compiled with C++23, maybe C++26, maybe C++41

If you're using a library as an actual installed package, you want the library to specify the C++ version after checking if it's already been set, because otherwise it will default to the minimum version you support via compile features instead of the maximum version available on the given platform that it can benefit from.

2

u/not_a_novel_account cmake dev Aug 07 '25

The compiler default might be what's most appropriate. "Newest standard available" is certainly the wrong default, which is why compilers don't do so themselves.

7

u/Plazmatic Aug 07 '25 edited Aug 07 '25

No, the compiler default is often very wrong for multiple reasons.

First, full stable support for a newer standard can be implemented, but not be the default for political/bureaucratic reasons, but reasons that don't apply to most developers/who you're targeting, for example the default in GCC is still C++17, but most people using our software would prefer to use features in c++20 or later (which would be disabled compiling the library in C++17 mode). In MSVC it's even worse, I believe C++14 is the default, despite it being the first to support many C++20 features among all the major compilers.

Second, sometimes a standard isn't considered standard because of a single feature which is wholly irrelevant to most users. In C++20's case it's modules. We don't use modules, our library is not a modules library, our clients don't use modules/don't care if our library isn't one. For example, the current stable version of GCC has two things not supported under C++20 on their official list of supported features, and both are modules related https://gcc.gnu.org/projects/cxx-status.html. Granted, modules is a pretty big part of C++20 in terms of what it adds, but reality kind of flies in the face of this idealized world about compilers properly setting defaults due to a number of non-really-technical factors.

Additionally sometimes we only care about library features (which are sometimes easier for compilers to add stably than other features), but doing so requires a dependence on a whole version of C++, even if we don't care about language feature support. std::span for example is, on it's own, a huge reason to want a library to be able to use C++20, but in your scenario, no one would be able to access this feature even if their compiler allowed for it with out both building and configuring the library themselves outside of something like VCPKG.

The idealism that the compiler makes the "right choice" here simply isn't true.

5

u/not_a_novel_account cmake dev Aug 07 '25

If they prefer to use C++20 and later, they should set CMAKE_CXX_STANDARD=20. I'm sure your customers would be frustrated by a project hardcoding CMAKE_CXX_STANDARD=11 in the CML, giving them no way to change it.

That's what I'm saying is wrong. Don't set the global, it's up to the person producing the build.

If the person producing the build does not request any standard, and the project does not communicate any requirements via target_compile_features(), then, as a last resort, when nothing has expressed any particular opinion about what standard should be used, the compiler default is the correct option.

2

u/Plazmatic Aug 07 '25

If they prefer to use C++20 and later, they should set CMAKE_CXX_STANDARD=20

That doesn't work unless they are consuming things as a submodule

I'm sure your customers would be frustrated by a project hardcoding CMAKE_CXX_STANDARD=11 in the CML, giving them no way to change it.

I'm not sure why you are making up/deleting things, but I explicitly called out a switch checking if it was already set.

6

u/not_a_novel_account cmake dev Aug 07 '25

I don't understand what you mean by that. A packager builds all the packages in their package repository, from which they fufill dependencies for other packages.

When building each of these packages, they set CMAKE_CXX_STANDARD as they see fit for their package collection. No submodules involved.

When doing project-local development, using something like vcpkg, the equivalent is the target triplet. In the target triplet you set up the settings you would like to be supplied for building all the dependencies, including CMAKE_CXX_STANDARD. Again no submodules.

It would be very frustrating if one dependency hardcoded the value in its CML and overrode the option communicated via the CMake -D option passed by vcpkg (or whatever packaging infrastructure, debhelper, makepkg, etc). And indeed, packagers ubiquitously provide patches that remove such hardcodings because they break the expectations of the surrounding packaging infrastructure.

→ More replies (4)

3

u/Own_Goose_7333 Aug 07 '25

I think you're wrong about FetchContent. My expectation is that I should be able to clone any CMake project and it should "just work" out of the box. If the project uses find_package(), then it won't work for dependencies not installed on the system. I think projects should default to declaring dependencies with FetchContent. Packagers can still override this to fallback to the find_package() behavior.

4

u/not_a_novel_account cmake dev Aug 07 '25

I sympathize, but you're the minority consumer of configuration systems. Most packagers expect to use their own dependency provisioning to provide for the build environment. Ie, a Debian packaging script or an Arch PKGBUILD have already described the build dependencies and setup an environment where they have installed everything exactly as they want it.

If the package is downloading and installing things on its own in that situation, the packager is forced to maintain a patch to disable, or at least inspect the project to figure out how to turn off, this behavior. That's a maintenance burden for the packager, and packagers are most of the people building any given C/C++ project.

3

u/quasicondensate Aug 23 '25 edited Aug 23 '25

All of what you write makes a lot of sense, but isn't this a very Linux-centric viewpoint, where one expects Linux package maintainers and the system package manager to do the heavy lifting? Developing applications for Windows in a not-so-big company, in my experience, there is no "packager" and the job is left to the devs. If we are lucky, a project can get by on Conan or Vcpkg, but more often than not, not all required dependencies are covered there, so we can choose whether we want to become proficient building Conan packages ourselves or forego the package manager and just use CMake.

What we often want is hermetic, CI-friendly builds, i.e. exactly the super-builds you mentioned. With "FetchContent" or "add_subdirectory" this is trivial, but having "find_package" being the norm forces us into inspecting all libraries to set up a manually defined "ExternalProject" hierarchy or god forbid an OS / pipeline glue layer orchestrating the build (breaking symmetry between local an CI builds in the process).

Don't get me wrong, I understand where you are coming from, and I also get why e.g. the behaviour of something like cargo is antithetical to Linux package management, but I'd still like to voice that personally, I am very grateful for any library that doesn't go by the "find_package() only" advice and lets itself being fetched no questions asked.

→ More replies (3)
→ More replies (7)

2

u/DXPower Aug 07 '25

What's wrong with target_include_directories?

5

u/not_a_novel_account cmake dev Aug 07 '25

It requires generator expressions to describe the movement of headers between the source and the install tree, and requires separate calls to install(FILES) for the installation of headers.

These things are handled automatically by target_sources(FILE_SET HEADERS).

If you're happy with target_include_directories(), then for you there's nothing wrong with it. It's not going to change or be deprecated or anything like that. But using it requires teaching generator expressions, and GenExs should generally be an expert-only tool.

3

u/joemaniaci Aug 07 '25

So it sounds to me like you're thinking of the context of creating a library where someone will depend on your .h to gain insight into the interface.

Whereas for me, I'm developing a company code base where my build is the final peg in the slot and no one will ever need my header files. So in that case target_include_directories is sufficient?

5

u/not_a_novel_account cmake dev Aug 07 '25

Correct, for code that never installs headers only consumes them, there's no advantage. So if all you ever use CMake for is applications, this sort of stuff is irrelevant to you.

As with a lot of C++ knowledge, there's a big gulf between the "library author" audience and the "I need my software to work" audience.