如何使用 CMake 声明像宏这样的函数

How to declare a function like macro using CMake

我找不到如何在 CMake 中像宏一样声明函数。

我需要一个像这样的宏函数:

#define MYFUNC(foo) QString( foo + "_suffix" )

由我的 CMakeLists.txt 文件定义。我试过了:

add_definitions("-DMYFUNC(foo)=QString\(foo+\"_suffix\"\)")

add_definitions("-DMYFUNC\(foo\)=QString\(foo+\"_suffix\"\)")

但 none 有效,编译器 (VS2015) 总是报告 MYFUNC 未定义...

来自Visual Studio documentation on /D

The /D option doesn't support function-like macro definitions. To insert definitions that can't be defined on the command line, consider the /FI (Name forced include file) compiler option.

为了完整起见,GCC 从命令行执行 support defining function macros

If you wish to define a function-like macro on the command line, write its argument list with surrounding parentheses before the equals sign (if any). Parentheses are meaningful to most shells, so you should quote the option. With sh and csh, -D'name(args…)=definition' works.

COMPILE_DEFINITIONS 的 CMake 文档明确指出不支持类似函数的宏:

The COMPILE_DEFINITIONS property may be set to a semicolon-separated list of preprocessor definitions using the syntax VAR or VAR=value. Function-style definitions are not supported. CMake will automatically escape the value correctly for the native build system (note that CMake language syntax may require escapes to specify some values).

考虑使用 -include 来强制包含定义宏的头文件。