Warm tip: This article is reproduced from serverfault.com, please click

Is it safe to run the C preprocessor several times on the same source?

发布于 2020-11-28 01:50:25

From my experience, the C preprocessor just behaves as no-op when running on a previously preprocessed source. But is this behaviour guaranteed by the standard? Or maybe an implementation could have a preprocessor that modifies previously preprocessed code and for example removes/modifies line directives, or performs other modifications that could confuse the compiler?

Questioner
cesss
Viewed
11
Acorn 2020-11-28 10:22:56

In general, preprocessing via cpp is not guaranteed to be idempotent (a noop after the first run). A simple counterexample:

#define X #define Y z
X
Y

The first invocation will yield:

 #define Y z
Y

The second one:

z

Having said that, valid C code shouldn't be doing something like that (because the output wouldn't be valid input for next stages of the compiler).

Moreover, depending on what you are trying to do, cpp has options like -fpreprocessed that may help.