与 C 预处理器“字符串化"相反 [英] Opposite of C preprocessor "stringification"

查看:18
本文介绍了与 C 预处理器“字符串化"相反的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 C 预处理器时,可以像这样对宏参数进行字符串化:

When using C preprocessor one can stringify macro argument like this:

#define TO_STRING(x) "a string with " #x

等使用时,结果如下:

TO_STRING(test) 将扩展为:"a string with test"

有什么方法可以反其道而行之吗?获取字符串文字作为输入参数并生成 C 标识符?例如:

Is there any way to do the opposite? Get a string literal as an input argument and produce a C identifier? For example:

TO_IDENTIFIER("some_identifier") 将扩展为:some_identifier

感谢您的回答.

对于那些想知道我需要它做什么的人:

For those wondering what do I need it for:

我想通过字符串标识符来引用我的 3D 引擎场景图中的节点,但同时避免在紧密循环中比较字符串.所以我想我会编写一个简单的工具,它将在编译的预构建步骤中运行并搜索预定义的字符串 - 例如 ID("something").然后对于每个这样的标记,它会计算括号之间的字符串的 CRC32 并生成一个带有包含这些数字标识符的#defines 的头文件.例如对于字符串 "something" 它将是:

I wanted to refer to nodes in a scene graph of my 3D engine by string identifiers but at the same time avoid comparing strings in tight loops. So I figured I'll write a simple tool that will run in pre-build step of compilation and search for predefined string - for example ID("something"). Then for every such token it would calculate CRC32 of the string between the parenthesis and generate a header file with #defines containing those numerical identifiers. For example for the string "something" it would be:

#define __CRC32ID_something 0x09DA31FB

然后,生成的头文件将包含在每个 cpp 文件中,使用 ID(x) 宏.ID("something") 当然会扩展为 __CRC32ID_something,因此实际上编译器会看到简单的整数标识符,而不是人类友好的字符串.当然,现在我将简单地满足于 ID(something) 但我认为使用引号会更有意义 - 一个不知道 ID 宏如何工作的程序员可以认为没有引号的 something 是 C 标识符,而实际上这种标识符根本不存在.

Then, generated header file would be included by each cpp file using ID(x) macros. The ID("something") would of course expand to __CRC32ID_something, so in effect what the compiler would see are simple integer identifiers instead of human friendly strings. Of course now I'll simply settle for ID(something) but I thought that using quotes would make more sense - a programmer who doesn't know how the ID macro works can think that something without quotes is a C identifier when in reality such identifier doesn't exist at all.

推荐答案

不,你不能取消字符串化.

No, you can't unstringify something.

这篇关于与 C 预处理器“字符串化"相反的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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