cpathcmakeout-of-source

Getting the compiler to find a Cmake-created file


I'm using the configure_file command in Cmake in a feature availability check as described on this page. That page suggests using the command like this:

configure_file(config.h.in config.h)

which will translate ${CMAKE_CURRENT_SOURCE_DIR}/config.h.in to ${CMAKE_CURRENT_BINARY_DIR}/config.h. But when I compile my program, the compiler only looks in ${CMAKE_CURRENT_SOURCE_DIR} for headers (e.g. config.h), not in ${CMAKE_CURRENT_BINARY_DIR}. So naturally, the compiler doesn't find config.h where it was generated, and the build fails.

What's the standard way to resolve this issue? Should I change CMakeLists.txt so that config.h gets created in the source directory? Or should I change it to add the build directory to the include path? (And really, why do I have to manually deal with this at all? [semi-rhetorical question])

This question concerns a similar issue but both options are suggested as possible solutions; I want to know if there's a standard practice, or if this indicates that I'm missing something about how Cmake is meant to be used.


Solution

  • Keeping your source tree 'pristine' is right, and not doing so is 'wrong' if you want to do multiple different builds for example, or if you want to be able to clean up a build by rm'ing the build dir (not sufficient if you're generating stuff to the source dir).

    Generate it in the build dir and add the include path.

    Set the variables

    set(CMAKE_INCLUDE_CURRENT_DIR ON)
    set(CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE ON)
    

    to make the corresponding build dir of each source dir automatically added, and to make that a transitive behavior for other targets to consume (so that foo doesn't have to add the build dir of bar explicitly for example).

    http://www.cmake.org/cmake/help/v3.0/manual/cmake-buildsystem.7.html#build-specification-and-usage-requirements