I've read in several places that a C struct can safely be defined multiple times, and yet I get a "redefinition of struct" error from gcc for multiply defining a struct (through multiple includes). A very simplified example looks like this:
foo.c:
#include "a.h"
#include "b.h"
int main(int argc, char *argv[]) {
struct bar b;
b.a = 2;
return 0;
}
a.h:
struct bar {
int a;
int b;
};
b.h:
#include "a.h"
struct buz {
int x;
int y;
};
If I run gcc foo.c
I get:
In file included from b.h:1:0,
from foo.c:2:
a.h:1:8: error: redefinition of ‘struct bar’
a.h:1:8: note: originally defined here
I know I haven't put any include guards and those will fix the compile error, but my understanding was that this should work nonetheless. I also tried two struct bar
definitions in foo.c and I get the same error message? So, can structs be defined mutiple times in C or not?
A struct in C can be declared multiple times safely, but can only be defined once.
struct bar;
struct bar{};
struct bar;
compiles fine, because bar is only defined once and declared as many times as you like.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With