9

我已经在几个地方读到 C 结构可以安全地定义多次,但是我从 gcc 中得到一个“重新定义结构”错误,用于多重定义一个结构(通过多个包含)。一个非常简化的示例如下所示:

富.c:

#include "a.h"
#include "b.h"

int main(int argc, char *argv[]) {
  struct bar b;
  b.a = 2;
  return 0;
}

啊:

struct bar {
  int a;
  int b;
};

:

#include "a.h"

struct buz {
  int x;
  int y;
};

如果我跑步,gcc foo.c我会得到:

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

我知道我没有放置任何包含防护,这些防护将修复编译错误,但我的理解是这仍然可以工作。struct bar我还在foo.c 中尝试了两个定义,但我得到了相同的错误消息?那么,是否可以在 C 中多次定义结构?

4

5 回答 5

12

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.

于 2012-04-09T15:00:22.810 回答
0

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.

于 2012-04-09T14:59:25.060 回答
0

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.

于 2012-04-09T14:59:32.707 回答
0

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

于 2012-04-09T14:59:34.567 回答
0

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

于 2012-04-09T15:00:23.820 回答