I want to use a value declared in my CMakeLists.txt in my C++ code. I\'ve tried to do like that :
ADD_DEFINITIONS( -D_MYVAR=1 )
and
<
Actually there is a much more elegant way to do this, that does not require to go through the C/C++ preprocessor. (I hate #ifdef
...)
In CMakeLists.txt
:
set( myvar "somebody" )
# Replaces occurrences of @cmake_variable@ with the variable's contents.
# Input is ${CMAKE_SOURCE_DIR}/main.cpp.in,
# output is ${CMAKE_BINARY_DIR}/main.cpp
configure_file( main.cpp.in main.cpp @ONLY )
In main.cpp.in
:
#include
int main(){
// myvar below gets replaced
std::cout << "hello @myvar@" << std::endl;
return 0;
}
Note, however, that a file so configured gets saved in ${CMAKE_BINARY_DIR}
, so you have to prefix it as such when listing it in the source files (as those default to ${CMAKE_SOURCE_DIR}
):
add_library( myproject foo.cpp bar.cpp ${CMAKE_BINARY_DIR}/main.cpp )