Why is #pragma considered a preprocessor directive?
Why is #pragma considered a preprocessor directive?
Because the C standard says so. It is specified in the chapter preprocessing directives, C17 6.10.6. Other than that, the standard is intentionally very vague with what #pragma
should do, since the whole purpose is to do something compiler-specific. Or in case the pragma isn't recognized - ignore it.
How a certain compiler handles the contents of a pragma internally isn't specified.
Some pragmas obviously need to be pre-processed, notably the kind that enables/disables certain compiler behavior like #pragma warning ...
etc. Lots of them must be evaluated during pre-processing or the compiler won't know how to compile the code.
Does preprocessor really do something with #pragma?
Yes, it evaluates it in translation phase 4: "Preprocessing directives are executed, macro invocations are expanded, and _Pragma unary operator expressions are executed."
Please note that having a pre-processor separated from the compiler is mostly a theoretical model. In reality the pre-processor and compiler are often rather tightly integrated with each other.
#pragma once
needs to be dealt with by the preprocessor, beacause its job is to replace include guards in ensuring that a file is included — using the preprocessor directive #include
— only once at a given location. #pragma pack
, on the other hand, needs to pass through the preprocessor unscathed because it is an instruction to the compiler about how to lay out data in memory.
To directly answer your questions:
Most pragmas, with the exception of
STDC FENV_ACCESS
,STDC FP_CONTRACT
andSTDC CX_LIMITED_RANGE
are not part of the C-Standard at all and as such it doesn't really matter whether or not they are "preprocessor directives" or not, the compiler is free to process them in any way it sees fit. For some pragmas it makes sense to process them during the preprocessing stage for others it doesn't. The main idea behind pragmas is that they can potentially influence the compilation process from the preprocessing stage onwards but unlike macros they are not expanded to anything.Yes, e.g. in the case of
#pragma once
as explained by other answers. But again, this is implementation specific and not prescribed by the standard.