Use variable from CMAKE in C++

后端 未结 3 1077
感动是毒
感动是毒 2021-01-27 03:16

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

<         


        
3条回答
  •  佛祖请我去吃肉
    2021-01-27 03:59

    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 )
    

提交回复
热议问题