跨头文件共享结构

时间:2020-06-05 00:31:18

标签: c struct

我不确定如何正确执行此操作。我需要从另一个头文件访问结构。我目前有5个文件。 foo.h foo.c bar.h bar.c main.c.

foo.h

#ifndef FOO_H_   /* include guard */
#define FOO_H_

typedef struct foostruct{
  int data;
} foostruct;

#endif

foo.c

#include "foo.h"
// empty

bar.h

#ifndef BAR_H_   /* include guard */
#define BAR_H_

typedef struct barstruct{
  int data;
  foostruct* foodata;
} barstruct;


#endif

bar.c

#include "bar.h"
#include "foo.h" // <-- thought i had to do it like this
// empty

main.c

#include <stdio.h>
#include "foo.h"
#include "bar.h"

int main () {
  printf("main\n");

  return 0;
}

编译错误

gcc -Wall -std=c11 -c main.c foo.c bar.c
In file included from bar.c:1:0:
bar.h:6:3: error: unknown type name 'foostruct'
   foostruct* foodata;
   ^
make: *** [Makefile:22: main.o] Error 1

1 个答案:

答案 0 :(得分:0)

将bar.h更改为:

typedef struct barstruct{
  int data;
  struct  foostruct* foodata;
} barstruct;

注意struct foostruct *

通过此更改,您不需要bar.h对foo.h的依赖。