如何使用 CMake 通过命令行定义 C++ 预处理器宏?

2023-08-28C/C++开发问题
12

本文介绍了如何使用 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 使用 CFLAGSCXX_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++ 预处理器宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6