I'm trying to write a state machine that slurps a source file and splits it into sections that are either the compiler's business or the preprocessor's business. Not a deep traversal, I'm just looking for sections that are either comments or preprocessor directives. (no macros, no conditionally compiled blocks, etc.)
Comments are simple enough, but I'm not 100% sure where it's legal to specify a preprocessor directive. For example, is the following line legal?
int i; #include <derp.h>
Are there any special cases where some directives are allowed and others are not?
I've searched google and SO and not found a question which answers this.
Please answer for BOTH C and C++, I tagged both knowingly and intentionally.
Preprocessor directives are lines of the source file where the first non-whitespace character is # , which distinguishes them from other lines of text. The effect of each preprocessor directive is a change to the text and the result is a transformation of the text that does not contain the directives nor comments.
These commands specifies which sections of the code to compile or how to handle specific errors and warnings. C# preprocessor directive begins with a # (hash) symbol and all preprocessor directives last for one line. Preprocessor directives are terminated by new line rather than semicolon .
Preprocessing directives are lines in your program that start with # . The # is followed by an identifier that is the directive name. For example, #define is the directive that defines a macro. Whitespace is also allowed before and after the # .
Preprocessor directives can appear anywhere, as long as they're the first non-whitespace token on the line. Accordingly, you can't write
int i; #define ThisIsntLegal SinceItsNotAtTheStart
But this would be:
int i;
#define Woohoo ThisIsLegal
Hope this helps!
C11 Standard (N1570, ISO/IEC 9899:201x) (Relevant section: s6.10 Prerocessing Directives, page 160)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With