C / C++ include inline code file
In certain cases, such as defining multiple classes or templates in a single header or source file in C or C++, it may be useful to include inline source code files to reduce code duplication.
This can be achieved by using the #include
directive with a file containing the inline code.
This technique is distinct from the use of
header files,
which are typically used to declare functions, classes, and other entities that are defined in a separate source file.
This technique is also distinct from the use of the
inline specifier on functions.
A traditional file suffix for include code files is .inc
or .inl
, but any suffix can be used.
Build systems detect changes to these included inline code files and rebuild the source file if necessary.
For example, CMake
detects
include dependencies (header, inline code) based on its own source parser, or some modern compilers manage dependencies themselves.
Makefiles with CMake uses the compiler itself or depend.make in each target build directory to track dependencies.
Ninja (with CMake or other build system such as Meson) specifies include dependencies via
depfiles
per source file, which may be observed for debugging with option ninja -d keepdepfile
Example
Here we assume a CMake project with source file main.cpp and inline source file myconst.inl.
main.cpp:
#include <iostream>
#include "myconst.inl"
int main() {
std::cout << "The value of MY_CONST is: " << MY_CONST << std::endl;
return 0;
}
myconst.inl:
constexpr int MY_CONST 42
cmake_minimum_required(VERSION 3.20)
project(InlineDemo LANGUAGES C CXX)
add_executable(demo main.cpp)
Observe that CMake will rebuild main.cpp if myconst.inl changes.
cmake -Bbuild
cmake --build build
touch myconst.inl
cmake --build build