C语言源文件之间的自定义类型(结构体)如何相互引用?

C语言源文件如何引用其他文件的重定义类型
比如
文件一:
typedef struct Node {
ElementType Data;
struct Node *next;
} LinkStack;

文件二:
在文件二如何使用LinkStack这个类型
直接 extern LinkStack; 貌似不行

一个示例如下(项目包含两个文件 Source.cpp,Source1.cpp

1. Source1.cpp源代码如下:

//Source1.cpp
struct people{
    int id;
    int age;
};

2. Source.cpp源代码如下:

//Source.cpp
#include<stdio.h>
#include "Source1.cpp"

int main(){

    struct people Tommy = { 1, 21 };

    printf("Tommy的id=%d,年龄=%d\n", Tommy.id, Tommy.age);
    getchar();
    return 0;
}

运行结果如下:

希望对你有帮助~

追问

C语言源文件如何引用其他文件的重定义类型

extern 重定义类型的原型
重定义类型的原型指哪个

追答

extern这样使用

extern struct people;

我的理解:结构体原型类似于函数原型吧

函数定义int fun(int a,int b){return a>b?a:b;}

其函数原型为 int fun(int a,int b);

所以我觉得结构体原型是 struct people;


这些概念 希望高手来解答,我也学习学习


此时上述示例的Sourc.cpp可以改为

#include<stdio.h>
#include "Source1.cpp"

extern struct people;

int main(){

    struct people Tommy = { 1, 21 };

    printf("Tommy的id=%d,年龄=%d\n", Tommy.id, Tommy.age);
    getchar();
    return 0;
}

程序仍然能正常运行

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-02-15

网路上可以查到范例, 希望你能开得起来.

http://bytes.com/topic/c/answers/763674-how-declare-structures-reference-each-other


另外贴上网页范例,

struct B;
struct A
{
struct B * b;
};
struct B
{
struct A * a;
};

只要有一个原型宣告就可以了, 如果在不同的源文件, include就相当於写在同一个文件中.

但是这样会导致include顺序性限制, 常用方法会是个别写外部参考的原型宣告, 建议以extern做标示.


---------------------------

我本来不太想直接写.


//temp1.h
struct temp2;
struct temp1{
struct temp2 *B;
};


//temp2.h
struct temp1;
struct temp2{
struct temp1 *A;
};


//temp_main.c
#include "temp1.h"
#include "temp2.h"
int main()
{
struct temp1 MainA;
struct temp2 MainB;
MainA.B = &MainB;
MainB.A = &MainA;
return 0;
}

本回答被提问者和网友采纳
第2个回答  2015-06-21
没能理解相互引用的意思,你是指在结构体定义时使用另一个结构体作为数据类型?

把两个结构体都定义在头文件中,然后互相包含,最上面加#program once 试试看,我不确定这样是否可以通过编译
第3个回答  2018-02-15
你直接把其中一个文件作为头文件导入,不就可以引用了么
第4个回答  推荐于2016-06-22
typedef struct tagMSG { // msg
HWND hwnd;
UINT message;
WPARAM wParam;
LPARAM lParam;
DWORD time;
POINT pt;
} MSG;

引用这个结构体只要
MGS msg;
即可用了