c - 如何使用 -D 选项将参数中的字符串化宏传递给 gcc

标签 c

我正在使用以下命令编译以下代码:
gcc test.c -D HEX=0xFFFF

#include <stdio.h>
#define NOERR 0
#define ERR 1

/*
 * Some Code 
 */
main()
{
    printf(#HEX);
}

我得到以下输出:

Ex2_03.c:33:9: error: stray ‘#’ in program
  printf(#HEX);
         ^
Ex2_03.c:33:2: warning: passing argument 1 of ‘printf’ makes pointer from integer without a cast [enabled by default]
  printf(#HEX);
  ^
In file included from Ex2_03.c:1:0:
/usr/include/stdio.h:362:12: note: expected ‘const char * __restrict__’ but argument is of type ‘int’
 extern int printf (const char *__restrict __format, ...);
            ^
Ex2_03.c:33:2: warning: format not a string literal and no format arguments [-Wformat-security]
  printf(#HEX);
  ^

最佳答案

你得到一个错误,因为 # 运算符只能在预处理器指令中使用。

您需要字符串化您的宏。字符串化需要一个两级宏:

#define STRINGIFY_(x)  #x
#define STRINGIFY(x)   STRINGIFY_(x)

printf(STRINGIFY(HEX));

关于c - 如何使用 -D 选项将参数中的字符串化宏传递给 gcc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28262502/

相关文章:

c - 允许 ((int *)p)++ 的任何 gcc 选项

c - fgets() 和 sscanf() 只存储数组中的第一个整数

c - 打开/dev/mem - 不允许操作

c - 在C中滚动文本文件

C语言如何格式化一个double到小数点后2位?

c - 提高求和的性能(C 版本)

c++ - 为什么 C++ 中可以用撇号分隔数字,而 C 中却不能?

c++ - char[] 和 char* 的区别?

c - struct initializer,typedef with visual studio

c - 函数参数是否占用本地内存空间?