How to define a C++ preprocessor macro through the command line with CMake?(如何使用 CMake 通过命令行定义 C++ 预处理器宏?)
问题描述
我尝试在 CMake 的命令行中设置预处理器宏.我试过了:
I try to set a preprocessor macro in the command line of CMake. I've tried:
set generator="Visual Studio 8 2005"
set params=-D MY_MACRO=1
cmake.exe -G %generator% %params% ..some_project
但它既没有在我编译时定义,也没有在 CMake 生成的文件中找到名称 MY_MACRO
,除了 CMakeCache.txt
它存在于形式:
but it's neither defined when I compile nor can I find the name MY_MACRO
in the files generated by CMake at all, except for CMakeCache.txt
where it's present in the form:
MY_MACRO:UNINITIALIZED=1
我该怎么做?
推荐答案
这个问题背后的动机是批量构建 3rd 方库,这就是我想避免修改 CMakeLists.txt 的原因.多年后,即使我不再需要它,我发现它很容易通过CMake 外部手段来实现:
The motivation behind the question was to batch build 3rd party libraries, which is why I wanted to avoid modifying CMakeLists. So years later, even though I don't need that anymore, I figured out that it's easily achievable by means external to CMake:
像往常一样调用 CMake,没有特殊标志.
Invoke CMake as usual, no special flags.
那么:
使用 MSVC: 编译器读取
CL
环境变量以获得额外的命令行参数.所以
With MSVC: The compiler reads the
CL
environment variable to get extra command line arguments. So
set CL=/DMY_MACRO=1 %CL%
然后调用 MSBuild 来完成它的工作.
then invoke MSBuild to do its job.
使用 Makefile: 生成的 makefile 使用 CFLAGS
和 CXX_FLAGS
变量作为 makefile 的预期用途.所以构建可以通过
With Makefiles: The generated makefiles use the CFLAGS
and CXX_FLAGS
variables as makefiles are expected to do. So the build can be started by
make CXX_FLAGS=-DMY_MACRO=1
或者通过设置相应的环境变量.
or by setting the corresponding environment variables.
这篇关于如何使用 CMake 通过命令行定义 C++ 预处理器宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 CMake 通过命令行定义 C++ 预处理器宏?


- 使用/clr 时出现 LNK2022 错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 从python回调到c++的选项 2022-11-16
- C++ 协变模板 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07