当前位置:网站首页>Cmake passing related macros to source code

Cmake passing related macros to source code

2022-06-23 01:38:00 summer_ sunrise

problem

Sometimes we need to be based on Cmake Different parameters are passed in during compilation , Run our different branches of code , Used to support different scenarios , So how to solve ?

Solutions

1、 How to use Cmake The compile command of passes in parameters ?
cmake Provide The following mechanisms Pass variables :

-D <var>:<type>=<value>, -D <var>=<value>
Create or update a CMake CACHE entry.

When CMake is first run in an empty build tree, it creates a CMakeCache.txt file and populates it with customizable settings for the project. This option may be used to specify a setting that takes priority over the project’s default value. The option may be repeated for as many CACHE entries as desired.

If the : portion is given it must be one of the types specified by the set() command documentation for its CACHE signature. If the : portion is omitted the entry will be created with no type if it does not exist with a type already. If a command in the project sets the type to PATH or FILEPATH then the will be converted to an absolute path.

This option may also be given as a single argument: -D:= or -D=.

2、 If a preprocessing macro is passed to a program ?
cmake Provide the following mechanism :add_compile_definitions

Add preprocessor definitions to the compilation of source files.

add_compile_definitions( …)
Adds preprocessor definitions to the compiler command line.

Example

CmakeLists.txt

if(${TEST} STREQUAL on)
    add_compile_definitions(TEST)
endif()
add_executable(cmake_demo main.cpp)

main.cpp

#include <iostream>

int main()
{
    
    #ifdef TEST
    std::cout << "TEST marco is define\n";
    #else
    std::cout << "TEST marco is not define\n";
    #endif
    
    return 0;
}

effect :

compile :cmake …/ -DTEST=on && make
function :./cmake_demo
Output :TEST marco is define

compile :cmake … && make
function :./cmake_demo
Output :TEST marco is not define

原网站

版权声明
本文为[summer_ sunrise]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202220515021614.html