在 C 中的 pragma 宏中插入双引号

Insert double quotes in a macro for pragma in C

我正在尝试用 C 语言创建一个宏,以便创建正确的 pragma 声明。

_pragma(section .BLOCK1) //Correct but deprecated
_pragma(section ".BLOCK1") //Correct without warning

以下代码有效,但编译器给了我一个警告(不推荐使用的声明):

#define DO_PRAGMA(x) _Pragma(#x)

#define PRAGMA(number) \
DO_PRAGMA(section .BLOCK##number)

PRAGMA(1)

如何在宏中包含双引号? 我已经尝试插入“\”,但它不起作用,因为字符串是直接解释的。

向宏添加双引号的正确方法确实是使用反斜杠,即:

#define STRING "\"string\""

"string" 现在存储在 STRING.

要将数字连接到您的宏字符串中,您可以执行类似的操作,但它需要存储在非 const char 数组中:

#define STRING "section \".BLOCK%d\""
#define CONV(str, n) sprintf(str, STRING, n)
//...
char str [50];
CONV(str, 1);
DO_PRAGMA(str);
//...

如果您还没有,请检查 pragma documentation and this usage example

您可以将其传递给辅助宏,它会扩展参数并将其字符串化。

#define _stringify(_x)  #_x

#define DO_PRAGMA(a) _Pragma(_stringify(a))

#define PRAGMA(number) \
    DO_PRAGMA(section _stringify(.BLOCK##number))