编译器通过此宏看到了什么? [英] What is the compiler seeing with this macro?

查看:118
本文介绍了编译器通过此宏看到了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一下:

  #define STRINGIFY(A) #A

如果我以后再写:

 STRINGIFY(hello)

编译器实际上看到了吗?

Is the compiler actually seeing this:

 #hello

我认为是#A前面的其他哈希值使我感到困惑.

I think it is that additional hash in front of #A that is confusing me.

推荐答案

否,编译器会将参数放在引号之间,结果是:

No, the compiler will put the argument between quotes, resulting in this:

"hello"

但是请注意,宏替换不会发生在###附近,因此,如果您确实需要对参数进行字符串化处理(即使是另一个宏),最好编写两个宏,第一个宏用于扩展参数,另一个宏用于添加引号:

However, beware that macro substitution doesn't take place near # and ##, so if you really need to stringify the argument (even if it's another macro) it's better to write two macros, the first one to expand the argument and the other one to add quotes:

#define STRINGIFY(x) STRINGIFY_AUX(x)
#define STRINGIFY_AUX(x) #x

或更笼统地说,如果您的编译器支持可变参数宏(在C99中引入):

Or more generally, if you're compiler supports variadic macros (introduced in C99):

#define STRINGIFY(...) STRINGIFY_AUX(__VA_ARGS__)
#define STRINGIFY_AUX(...) #__VA_ARGS__

如果您确实需要一个在函数的开头粘贴#的类似函数的宏,我认为您需要它来生成一个字符串(否则您将为编译器创建一个无效的令牌),因此您可以简单地生成两个字符串文字,编译器将粘贴"这些文字:

If you really need a function-like macro that paste a # at the beginning of the argument, I think you need it to generate a string (otherwise you'd make an invalid token for the compiler), so you could simple generate two string literals that the compiler will "paste":

#include <stdio.h>

#define STRINGIFY(...) STRINGIFY_AUX(__VA_ARGS__)
#define STRINGIFY_AUX(...) #__VA_ARGS__

int main(void)
{
  puts(STRINGIFY(#) STRINGIFY(hello));
}

main主体在预处理器输出中将如下所示:

The main body will look like this in the preprocessor output:

puts("#" "hello");

我希望这不是导致不确定的行为的预处理器的一个死角,但这应该不是问题,因为我们不会生成另一个预处理器指令.

I hope this is not an obscure corner of the preprocessor that results in undefined behavior, but it shouldn't be a problem since we're not generating another preprocessor instruction.

这篇关于编译器通过此宏看到了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆