制作的东西都一个C和一个字符串? [英] Making something both a C identifier and a string?

查看:190
本文介绍了制作的东西都一个C和一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你想生成标识符和字符串匹配列表

Say you want to generate a matched list of identifiers and strings

enum
{
NAME_ONE,
NAME_TWO,
NAME_THREE
};

myFunction(NAME_ONE, "NAME_ONE");
myFunction(NAME_TWO, "NAME_TWO");
myFunction(NAME_THREE, "NAME_THREE");

..不重复自己,没有自动生成code,使用C / C ++宏

..without repeating yourself, and without auto-generating the code, using C/C++ macros

初始猜测:

您可以添加包含文件的#include

You could add an #include file containing

myDefine(NAME_ONE)
myDefine(NAME_TWO)
myDefine(NAME_THREE)

然后使用两次,如:

Then use it twice like:

#define myDefine(a) a,
enum {
#include "definitions"
}
#undef myDefine

#define myDefine(a) myFunc(a, "a");
#include "definitions"
#undef myDefine

#定义,但不会让你把一个字符串中的参数?

but #define doesn't let you put parameters within a string?

推荐答案

有关你的第二个的#define,你需要使用#preprocessor运营商,像这样的:

For your second #define, you need to use the # preprocessor operator, like this:

#define myDefine(a) myFunc(a, #a);

这将参数转换为字符串。

That converts the argument to a string.

这篇关于制作的东西都一个C和一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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