如何在C或C ++中打印宏名称 [英] How to print macro name in c or c++

查看:1091
本文介绍了如何在C或C ++中打印宏名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在c或c ++中打印宏名称 例如:

How to print macro name in c or c++ eg:

#define APINAME abc
#define PRINTAPI(x) printf("x")

我要打印PRINTAPI(APINAME)而不是"abc"

I want to print PRINTAPI(APINAME) and not "abc"

推荐答案

宏是预处理程序,在编译代码之前,宏将被其关联的语句替换.因此,您没有机会在运行时使用宏名称.但是,您可以在编译时生成字符串名称:

Macros are pre-processors and they will be replaced by their associated statement before compiling the code. So, you have no chance to have the macro names in run-time. But, you can generate the string name in compile-time:

#define APINAME abc
#define PRINTAPI(x) std::cout << #x << std::endl;

int main()
{
    PRINTAPI(APINAME);
}

输出

APINAME

在宏中,运算符#将输入参数设置为字符串文字(字符串化)

In macros the operator # makes the input parameter to a string literal (stringify)

这篇关于如何在C或C ++中打印宏名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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