Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is it legal to specify a preprocessor directive?

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.

like image 908
Wug Avatar asked Jun 09 '13 21:06

Wug


People also ask

Where are preprocessor directives defined?

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.

Where are preprocessor directives defined in C#?

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 .

Which is a valid preprocessor directive?

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 # .


1 Answers

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)

like image 78
templatetypedef Avatar answered Oct 07 '22 05:10

templatetypedef