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
<
Thanks to πάντα ῥεῖ
His solution works for my first question, and I've could do that :
CMakeLists.txt:
ADD_DEFINITIONS( -D_VAR=\"myValue\" )
main.cpp:
#include <iostream>
#ifdef _VAR
#define TXT _VAR
#else
#define TXT "nobody"
#endif
int main(){
std::cout << "hello " << TXT << " !" << std::endl;
return 0;
}
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 <iostream>
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 )
add_definitions ( -DVARNAME=... )
is the correct way of using add_definitions.
To check for a constant then, use
#ifdef VARNAME
...
#endif