Search code examples
ccmakeconfiginclude-path

How to ensure a generated config.h file is in the include path?


I use CMake to build a C project. Specifically, I use the following line:

configure_file(config.h.in config.h @ONLY)

this works fine as long as I build in the source directory. However, if I build elsewhere, the config.h file is created in /path/to/build/dir/config.h rather than in the source directory - and that's not part of the include path. How can I have CMake...

  • Ensure this specific file is included, or
  • Have the C compiler look both under the original source dir and under the build dir for include files?

Solution

  • There is an automatism for include directories with CMAKE_INCLUDE_CURRENT_DIR in CMake:

    set(CMAKE_INCLUDE_CURRENT_DIR ON)
    

    If this variable is enabled, CMake automatically adds CMAKE_CURRENT_SOURCE_DIR and CMAKE_CURRENT_BINARY_DIR to the include path for each directory.

    So I prefer to individually have the following call on a need-by basis in my CMakeLists.txt:

    include_directories("${CMAKE_CURRENT_BINARY_DIR}")
    

    Edit: Thanks for the hint of @zaufi, if your generated header file has a target scope then you should prefer (CMake >= Version 2.8.12) to make it only visible to that target (not globally to all targets) with:

    target_include_directories(MyLibrary PRIVATE "${CMAKE_CURRENT_BINARY_DIR}")
    

    Note: For source files with relative paths CMake looks in both directories CMAKE_CURRENT_SOURCE_DIR and CMAKE_CURRENT_BINARY_DIR.