1. 程式人生 > >CMAKE 中 add_definitions的用法.

CMAKE 中 add_definitions的用法.

1.官方的說明

Adds -D define flags to the compilation of source files.

add_definitions(-DFOO -DBAR ...)

Adds definitions to the compiler command line for sources in the current directory and below. This command can be used to add any flags, but it is intended to add preprocessor definitions. Flags beginning in -D or /D that look like preprocessor definitions are automatically added to the 

COMPILE_DEFINITIONS directory property for the current directory. Definitions with non-trivial values may be left in the set of flags instead of being converted for reasons of backwards compatibility. See documentation of the directorytargetsource file COMPILE_DEFINITIONS properties for details on adding preprocessor definitions to specific scopes and configurations.

https://cmake.org/cmake/help/v3.0/command/add_definitions.html2.

2.小例子:

假設專案是以CMakeLists.txt 構建的.

程式碼中通過巨集 USE_MACRO 作為區分.

...

#ifdef USE_MACRO

...

#endif

我們可以通過在專案中的CMakeLists.txt 中新增如下程式碼控制程式碼的開啟和關閉.

+ OPTION(USE_MACRO

+  "Build the project using macro"

+  OFF)

+ IF(USE_MACRO)

+  add_definitions("-DUSE_MACRO")

+ endif(USE_MACRO)

3.執行構建專案的時候可以新增引數控制巨集的開啟和關閉.

開啟: cmake  -DUSE_MACRO=on ..

關閉: cmake  -DUSE_MACRO=off ..