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?
That is actually a long running half-bug half-design-inconsistency in the gcc itself.
It boils down to a "#pragma is a statement". Pragmas can be used anywhere a statement can, but not be part of another statement. Even if other preprocessor's words like #define and #ifdef can.
Said that, the easiest way to solve your problem is to move the #pragma message out of struct definition and replace it with a special define:
#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
#define HIT_STRUCT_WITH_42
.id = 42,
#endif
.name = "Example Name",
.value = 3.14f,
};
#ifdef HIT_STRUCT_WITH_42
#pragma message("Hello from structure")
#endif
int main() {
printf("ID: %d\n", example.id);
return 0;
}