Home > OS >  How do c/c preprocessors work when encountering unknown directives?
How do c/c preprocessors work when encountering unknown directives?

Time:02-24

Do c/c preprocessors process all lines that begin with #? Does is errors out when encountering unknown macros or will it just ignore them?

for an example,

#include <stdio.h>

#hello
int main(){
    printf("Hello World!");
    return 0;
}

what happens in this situation?will it produce an error or will it work (ignoring #hello line)?

CodePudding user response:

The language grammar specifies all pre-processor directives that exist in the language. If the program doesn't conform to the grammar, then the program has a syntax error. Hence the program is ill-formed and the language implementation is required to issue a diagnostic message and is free to refuse to proceed.

CodePudding user response:

C

Syntactically, #hello is a "non-directive" preprocessing directive.

C17/C18 section 6.10 paragraph 9 (newly added in C17/C18) says:

The execution of a non-directive preprocessing directive results in undefined behavior.

"Undefined behavior" does not necessarily mean that the compiler will fail to translate the code or issue a diagnostic. It could behave in a documented manner, for example if the directive is part of an extension to the C language.

C

Syntactically, #hello is a "conditionally-supported-directive" preprocessing directive.

C 20 section 15.1 paragraph 2 says:

A conditionally-supported-directive is conditionally-supported with implementation-defined semantics.

"Conditionally-supported" means that an implementation is not required to support it. Implementations need to document all conditionally-supported constructs that they do not support. (In the case of conditionally-supported-directives, I guess that would amount to documenting that none of them are supported, or documenting the semantics of those that are supported.)

CodePudding user response:

An unrecognized preprocessing directive error will rise, and your code won't compile

  • Related