如何使用 CMake 通过命令行定义 C++ 预处理器宏? [英] How to define a C++ preprocessor macro through the command line with CMake?

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆