Multi-pass C preprocessor [closed]

走远了吗. 提交于 2019-12-14 01:25:12

问题


Is it remotely sane to apply the C preprocessor to the same codebase multiple times (specifically, twice in sequence?)

For instance, having declarations such as the following:

##define DECLARE(FILE) # define DECLARATIONS \
                       #   include FILE \
                       # undef DECLARATIONS

Have you ever seen such an idiom before? If so, what codebase? Can you link it? What sort of patterns would be followed to compile a project doing something like this? Can the CPP as it stands be made to do this, or do I need to write a meta-preprocessor to “hide” the single-hash declarations while processing the double-hash declarations, and so on?


回答1:


I think when you need multiple CPP passes, you might want to consider m4 or some other sophisticated macro system/code generator. I think it will be hard to do what you want, and since you are going to be changing your build process for this anyway, look at other templating or macro systems.




回答2:


Oh wow, why would you want to do this? I am sure GCC could be coerced into doing something like this with some clever make tricks (use the -E flag for GCC) but I can't imagine anyone being able to maintain it later.




回答3:


Google threw this up, so here's a four-years-late use case for multiple (pre)compilation passes.

The largest benefit to multiple-pass compilation that I can see comes from optionally preprocessing the file. Specifically, when one would like to see the preprocessed source without including the very large standard headers at the top. E.g.,

#ifdef PRECOMPILATION
#ifdef TMPINCLUDE
#error "This stunt assumes TMPINCLUDE isn't already defined"
#endif
#define TMPINCLUDE #include <stdlib.h>
TMPINCLUDE
#undef TMPINCLUDE
#else
#include <stdlib.h>
#endif

This will compile as normal in the absence of PRECOMPILATION, but if compiled as gcc -E -P -DPRECOMPILATION or similar, will translate into a source file containing all your code, post expansion, and the #include statement at the top. So it's still valid code and can also be compiled from the already-preprocessed file.

Macros are unpopular in the C and C++ world. I would like to release a plausibly useful library to the wider world, but it's very heavily based on macros to reduce code duplication. Using an either-one-or-two pass compilation model means I can use the library directly, macros and all, in my own work, but can also release a sanitised version which only uses the preprocessor to include standard libraries.

Whether that is remotely sane or not is rather subjective.



来源:https://stackoverflow.com/questions/5136471/multi-pass-c-preprocessor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!