Elektito
Elektito

Reputation: 4155

Can a C struct be defined multiple times?

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?

Upvotes: 9

Views: 4393

Answers (5)

SirGuy
SirGuy

Reputation: 10780

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.

Upvotes: 12

mensi
mensi

Reputation: 9846

The same symbol in the same scope cannot be defined twice. What you are probably referring to is that it is safe to include the struct from two different C files which essentially means that they are defined twice (since there is no export) and sharing these structs won't be a problem, since they are compiled to the same memory layout

Upvotes: 0

Jason Huntley
Jason Huntley

Reputation: 3877

You don't have #ifdef macros in your header file. If you include your headers in multiple source files, you will encounter that error.

Upvotes: 0

Lefteris
Lefteris

Reputation: 3256

No they can't be defined multiple times and that is why you have #ifndef include guards and should use them.

Having

#include "a.h"

inside b.h header file means you redefine bar. If you had #ifndef include guards this would not be happening.

Upvotes: 0

Jonathan Wood
Jonathan Wood

Reputation: 67345

The struct can only be defined once for each file you compile. Here, you are including a.h twice. (Once directly and once via b.h.)

You need to change your code so that the symbol is only defined once for a given source file.

Upvotes: 0

Related Questions