可以将宏的名称用作常规宏和字符串

时间:2016-02-19 09:19:46

标签: c

在类似Object的宏中,宏的名称可以用作常规宏,也可以用作c代码中的字符串

#define MAX   0x1001
#define ANNE  0x1002
#define LENE  0x1003

void main()
{
 printf("%s is the name and number is %d ",MAX, MAX);
}

2 个答案:

答案 0 :(得分:4)

#define MAX   0x1001
#define EXPLAIN_MACRO_INT(x) \
      printf("%s is the name and the number is %d\n", #x, x);

小心传递给此_INT宏的参数。这是为了打印整数。类似地为其他类型编写宏。

用法:

EXPLAIN_MACRO_INT(MAX)

输出:

MAX是名称,数字是4097

更通用

或者如果您想使用它

printf("%s is the name and the number is %d\n", EXPLAIN_MACRO(MAX));

然后

#define EXPLAIN_MACRO(x) #x, x

第二个版本可以与所有类型的参数一起使用 - 但现在你必须注意printf中的格式。

输出相同:

MAX是名称,数字是4097

答案 1 :(得分:0)

https://gcc.gnu.org/onlinedocs/cpp/Stringification.html

使用字符串化:

 #define MAX   0x1001
 #define xstr(s) str(s)
 #define str(s) #s
 #define foo 4

printf("%s is the name and number is %d ", str(MAX), MAX);

// note xstr(MAX) would expand to "1234"
相关问题