通过 CMake 定义预处理器宏?

2021-12-26 00:00:00 cmake c++ c-preprocessor

如何通过 CMake 定义预处理器变量?

How do I define a preprocessor variable through CMake?

等效的代码是 #define foo.

推荐答案

很长一段时间,CMake 都有用于此目的的 add_definitions 命令.但是,最近该命令已被更细粒度的方法(用于编译定义、包含目录和编译器选项的单独命令)所取代.

For a long time, CMake had the add_definitions command for this purpose. However, recently the command has been superseded by a more fine grained approach (separate commands for compile definitions, include directories, and compiler options).

使用新add_compile_definitions的示例:

add_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION})
add_compile_definitions(WITH_OPENCV2)

或者:

add_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION} WITH_OPENCV2)

这样做的好处在于,它规避了 CMake 为 add_definitions 设置的破旧诡计.CMake 是一个如此破旧的系统,但他们终于找到了一些理智.

The good part about this is that it circumvents the shabby trickery CMake has in place for add_definitions. CMake is such a shabby system, but they are finally finding some sanity.

在此处查找有关用于编译器标志的命令的更多说明:https://cmake.org/cmake/help/latest/command/add_definitions.html

Find more explanation on which commands to use for compiler flags here: https://cmake.org/cmake/help/latest/command/add_definitions.html

同样,您可以按照 Jim Hunziker 的回答中的说明针对每个目标执行此操作.

Likewise, you can do this per-target as explained in Jim Hunziker's answer.

相关文章