Use variable from CMAKE in C++

左心房为你撑大大i 提交于 2020-05-24 03:27:07

问题


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

#if -D_MYVAR == 1
    #define var "someone"
#else
    #define var "nobody"
#endif
int main(){
    std::cout << "hello" << var << std::endl;
    return 0;
}

But it doesn't work, and I don't understand why. Maybe I don't use ADD_DEFINITIONS correctly...

Ideally, I wish do something like that :

ADD_DEFINITIONS( -D_MYVAR=\"someone\" )

and

#define var D_MYVAR

int main(){
    std::cout << "hello" << var << std::endl;
    return 0;
}

Is it possible ?

Thanks !


回答1:


add_definitions ( -DVARNAME=... )

is the correct way of using add_definitions.

To check for a constant then, use

#ifdef VARNAME
...
#endif



回答2:


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;
}



回答3:


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 )


来源:https://stackoverflow.com/questions/24488239/use-variable-from-cmake-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!