从源中提取预处理器符号 [英] Extracting preprocessor symbols from source

查看:57
本文介绍了从源中提取预处理器符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种提取代码中使用的所有预处理器符号的方法.
例如,如果我的代码如下:

I'm looking for a way to extract all preprocessor symbols used in my code.
As an example, if my code looks like this:

#ifdef FOO
#endif

#if ( BAR == 1 && \
      defined (Z) )
#endif

我想获取列表 [FOO,BAR,Z] 作为输出.

I'd like to get the list [FOO,BAR,Z] as the output.

我发现一些帖子建议 gcc -E -dM ,但这显示了预处理器将应用于代码的所有符号.
相反,我想要的是在代码中实际使用的所有符号的列表.

I found some posts suggesting gcc -E -dM, but this displays all symbols that the preprocessor would apply to the code.
What I want, in contrast, is a list of all symbols actually used in the code.

有什么建议吗?

推荐答案

这很简单.您只需按照一致的预处理程序的方式完全解析源代码,并使用正确的C或C ++版本支持即可.好吧,我在开玩笑,如果您仅支持更高版本,则您的代码可能会在较旧版本上产生正确的结果-甚至应该对此进行完全控制.

That's quite simple. You have just to parse the source code exactly the way a conformant pre-processor would, and with the correct C or C++ version support. Ok, I'm joking, if you support only the later version, your code is likely to produce correct results on older versions - but even this should be thoroughly controlled.

现在更加认真.正如您可以要求预处理器为您提供所有已定义符号的列表一样,您可以简单地对源进行 tokenize ,并从该列表中识别出所有紧随初始#define或#之后的令牌undef.这部分应该可以在lex + yacc上实现.

More seriously now. As you can ask the pre-processor to give you the list of all defined symbols, you can simply tokenize the source, and identify all tokens from that list that are not immediately following an initial #define or #undef. This part should be reasonably feasable with lex+yacc.

我能想到的唯一选择是使用真正的编译器的代码(Clang应该比gcc更容易,但不确定)丢弃所有代码生成并始终存储每个宏用法.

The only alternative I can imagine would be to use the code of a real compiler (Clang should be easier than gcc but unsure) discard all code generation and consistently store every macro usage.

TL/DR:但是,如果您接受的话,那将是一项艰巨的工作:如果您不能这样做,请远离...

TL/DR: however you take it, it will be a hard work: if you can do without, keep away from that...

这篇关于从源中提取预处理器符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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