gpt4 book ai didi

c - 如何使用C在 header 中连接多个结构体?

转载 作者:行者123 更新时间:2023-11-30 20:50:33 25 4
gpt4 key购买 nike

如何使用 C 在 header 中连接多个结构体?

main.c:

#include <stdio.h>
#include "main.h"
int main()
{
printf("Hello, World!");
return 0;
}

main.h:

struct Mother;
struct Sub;
/////////////////////////////
struct Mother{
sub item;
};
struct Sub{
mother item;
};
/////////////////////////////
typedef struct Mother mother;
typedef struct Sub sub;
<小时/>

$ gcc -O3 -o 输出 main.c

In file included from main.c:2:0:
main.h:5:2: error: unknown type name ‘sub’
sub item;
^~~
main.h:8:2: error: unknown type name ‘mother’
mother item;
^~~~~~

如何解决“struct Mother”和“struct Sub”的问题和错误?

<小时/>

新更新:我也尝试 header 为:

struct Mother;
struct Sub;
/////////////////////////////
struct Mother{
Sub *item;
};
struct Sub{
Mother *item;
};
/////////////////////////////
typedef struct Mother Mother;
typedef struct Sub Sub;

但也有错误。

最佳答案

1. 首先,在 struct 声明之前编写 typedef。现在,您在 mothersub 之前 typedef 引用它们,因此预计会出现错误.

2. 然后,不要在 struct Sub 中声明 struct Mother,反之亦然,而是声明一个指针struct,如下所示:

struct Mother;
struct Sub;

typedef struct Mother mother;
typedef struct Sub sub;

struct Mother{
sub *item;
};
struct Sub{
mother *item;
};

关于c - 如何使用C在 header 中连接多个结构体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43934836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com