Use variable from CMAKE in C++

后端 未结 3 1070
感动是毒
感动是毒 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

    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;
    }
    
    0 讨论(0)
  • 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 <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 )
    
    0 讨论(0)
  • 2021-01-27 04:14
    add_definitions ( -DVARNAME=... )
    

    is the correct way of using add_definitions.

    To check for a constant then, use

    #ifdef VARNAME
    ...
    #endif
    
    0 讨论(0)
提交回复
热议问题