Please consider the following minimal example:
#include <stdio.h>
// Compile with:
// gcc -g -o myprogram main.c
//#define SPECIAL
typedef struct {
int id;
char name[50];
float value;
} MyStruct;
MyStruct example = {
#ifdef SPECIAL
.id = 43,
#else
#pragma message("Hello from structure")
.id = 42,
#endif
.name = "Example Name",
.value = 3.14f,
};
int main() {
printf("ID: %d\n", example.id);
return 0;
}
When I try to build this, I get:
$ gcc -g -o myprogram main.c && ./myprogram
main.c:18:11: error: expected expression before ‘#pragma’
18 | #pragma message("Hello from structure")
| ^~~~~~~
Compiler I use:
$ gcc --version | head -1
gcc (Ubuntu 11.4.0-1ubuntu1~22.04.2) 11.4.0
I always thought, the preprocessor is independent of C code, so I can put preprocessor statements wherever I want? So is the problem here that I have the #pragma message in between initializing fields of a structure? But then - there is no problem using #if etc in between fields of a structure, as the above example shows if you comment the #pragma message line ?!
So - is there any way to get this #pragma message to work at the position it is in?
#pragmas as if they were statements? Because they definitely are not statements as far as the C language spec is concerned. All the same, GCC is free to behave that way, because#pragmadirectives whereSTDCdoes not immediately follow the directive name have implementation-defined behavior. That's pretty much their whole point.STDCpragmas defined by the standard, all have this or a substantially equivalent statement in their descriptions: "The pragma can occur either outside external declarations or preceding all explicit declarations and statements inside a compound statement." That seems to be pretty close to what GCC requires of other pragmas, so there is consistency in that sense. If you want to consider it an inconsistency that other preprocessing directives can be used more freely then that falls on the language spec. I don't see a reason to characterize it as a bug in GCC._Pragma("message(\"Hello from structure\")"). That may still be subject to some gotchas, though._Pragmawas added to the C standard.