问题描述
我正在尝试在C中创建一个宏,以创建正确的编译指示。
_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 _stringify(_x) #_x
#define DO_PRAGMA(a) _Pragma(_stringify(a))
#define PRAGMA(number) \
DO_PRAGMA(section _stringify(.BLOCK##number))
,
向宏添加双引号的正确方法确实是使用反斜杠,即:
#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和this usage example。