Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a C struct be defined multiple times?

Tags:

c

struct

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?

like image 484
Elektito Avatar asked Feb 02 '23 06:02

Elektito


1 Answers

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.

like image 109
SirGuy Avatar answered Feb 05 '23 18:02

SirGuy