问题
I am implementing a C macro preprocessor (C99)...
I am surprised by the following behaviour....
Ex1:
#define PASTE(x) X_##x #define EXPAND(x) PASTE(x) #define TABSIZE 1024 #define BUFSIZE TABSIZE PASTE(BUFSIZE) EXPAND(BUFSIZE)
expands to:
X_BUFFSIZE X_1024
Ex2:
#define EXPAND(s) TO_STRING(s) #define TO_STRING(s) #s #define FOUR 4 TO_STRING(FOUR) EXPAND(FOUR)
Expands to:
"FOUR" "4"
I have gone through the "free" standard of C but I couldn’t find following things...
- Actually how many passes preprocessor performs?
- Does it replace one macro first then other and so on
- or does it store & replace them as
#define
s are encountered one by one? - Whether file inclusion is done first or the macro expansion?
回答1:
You should read this page for starters. It contains gems such as:
The C standard states that, after any parameters have been replaced with their possibly-expanded arguments, the replacement list is scanned for nested macros. Further, any identifiers in the replacement list that are not expanded during this scan are never again eligible for expansion in the future, if the reason they were not expanded is that the macro in question was disabled.
I think one can infer from this that there is no fixed number of passes: each time a macro expansion happens (which generates a "replacement list"), the newly created text is scanned for further expansions. It's a recursive process.
回答2:
Actually how many passes preprocessor performs?
- It replaces all occurences of
# PARAMETER
by the stringification of that parameter - It joins all tokens that have a
##
inbetween - it replaces all remaining ocurences of the parameters by their value
- It recursively expands the replacement text for occurences of other macros. (The macro itself is blocked in these recursive calls.)
Does it replace one macro first then other and so on or does it store & replace them as #defines are encountered one by one?
It replaces macros in the order it encounters them in the program text, or during the recursive replacement as described above.
Whether file inclusion is done first or the macro expansion?
first the argument of an #include
is expanded if it doesn't consist in something that is either enclosed in <>
or ""
. That then must lead to exactly that something that is in <>
or in ""
来源:https://stackoverflow.com/questions/15430369/can-anybody-please-explain-the-behavour-of-c-preprocessor-in-following-examples