You may implement this with configure_file
and an auxiliary file. E.g.
// File: support_macros.h.in (auxiliary file)
// This file is generated by CMake. Don't edit it.
#define VAR "@VAR@"
// File: main.c
#include "support_macros.h"
#include <stdio>
int main()
{
puts(VAR);
// ...
}
# File: CMakeLists.txt
project(proj)
cmake_minimum_required(VERSION 3.0)
# Not needed
# add_definitions(-DSTR)
add_executable(main main.c)
# -- Generate support_macros.h from support_macros.h.in
set(IN_FILE "${CMAKE_SOURCE_DIR}/support_macros.h.in")
set(GENERATED_FILE_PATH "${CMAKE_BINARY_DIR}/GeneratedFiles")
set(OUT_FILE "${GENERATED_FILE_PATH}/support_macros.h")
configure_file("${IN_FILE}" "${OUT_FILE}" @ONLY)
# -- Make sure main.c will be able to include support_macros.h
target_include_directories(main PRIVATE "${GENERATED_FILE_PATH}")
Then, call cmake
passing a value for VAR
:
$ cmake .. -DVAR="some text"
Note: by putting quotes around @VAR@
in support_macros.h.in
, your main.c
will compile even if you don't pass a value for VAR
to cmake
.