How to properly include header files

I’m so sorry if this has been asked before but I’ve scoured around and I can’t find a suitable answer for my question! Let’s say my project structure is as follows:

  • Engine
    • Components
      • bunch of .h files
    • Tools
      • Vector.cpp
      • Vector.h
    • main.cpp

I want CMake to build a Visual Studio project from this called “Engine” with the exact same folder structure and set the “include directories” to point to C:/Projects/Engine. That way all I have to do is #include Tools/Vector.h for instance in any .cpp file. I don’t want to make a library for each of my “tools”. How can this be done?

I assume you are building an executable (because of main.cpp) and that your CMakeLists.txt resides in the Engine/ directory. Then setting the include paths should be as easy as:

target_include_directories(Engine PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}")

If your building a library instead or your executable provides any INTERFACE/PUBLIC headers (e.g. for plugins) then once you intend to package/install your artifacts you need to use the $<BUILD_INTERFACE:...> and $<INSTALL_INTERFACE:...> generator expressions as documented for the target_include_directories() command.

For managing the folder structure of the generated Visual Studio project have a look at the source_group() command. But since Visual Studio has built-in support for CMake since 2015 (IMHO pretty decent one since 2019), I would recommend using that instead of generating solution and project files. With the built-in support you have a direct view onto your directory structure, have to bother less about IDE-specific things and can leverage many nice features like presets or faster builds with Ninja.