I'm trying to use CMake to create some header files that will be read in by my source code. My problem is that when I run cmake ..
in my build/
folder, it generates the configuration file inside my build folder, and then when I run the generated Makefile it fails to find the header.
Of course I could fix this by using #include "build/config.h"
from my C++ file rather than #include "config.h"
, but it seems like my C++ code shouldn't know about my build folder (I might want more than one possible build setup, for example). Similarly, I could ask CMake to write the header file to the source directory, but that's breaking the out-of-source build setup.
Is there a way of getting CMake to generate a Makefile that will build, subject to these constraints?
My CMakeLists.txt is below. It reads in config.h.in
and outputs config.h
.
cmake_minimum_required(VERSION 3.9)
project(fftb)
set(CMAKE_CXX_STANDARD 17)
set(fftb_VERSION_MAJOR 0)
set(fftb_VERSION_MINOR 0)
configure_file(
"${PROJECT_SOURCE_DIR}/config.h.in"
"${PROJECT_BINARY_DIR}/config.h"
)
add_executable(fftb main.cpp config.h.in)
My config.h.in
is below, it #defines the version to be used in main.cpp
#ifndef FFTB_CONFIG_H_IN_H
#define FFTB_CONFIG_H_IN_H
#define fftb_VERSION_MAJOR @fftb_VERSION_MAJOR@
#define fftb_VERSION_MINOR @fftb_VERSION_MINOR@
#endif //FFTB_CONFIG_H_IN_H
My main.cpp
is below, it includes the auto-generated config.h
and outputs it.
#include <iostream>
#include "config.h"
int main() {
std::cout << "Version " << fftb_VERSION_MAJOR << "." << fftb_VERSION_MINOR << std::endl;
return 0;
}