//file: head.h
struct test
{ int i;
char j;
}; // 这里不能定义任何变量,因为头文件被许多文件包含,会出现重复定义
extern struct test *right; // 申明结构体变量 right 在其它文件中定义
/*******************************************************/
//file: use.c
struct test *right; // 在这里将 right 定义为全局变量
//file: other.c
#include "head.h" // 只要将头文件包含进去,任何文件都可以调用 right;
void over()
{ printf("%c",right->j); // 直接调用结构体变量 right 的成员
}
感谢大家的参与!
楼下有些朋友提到了这种观点:一个变量可以多次申明,不管是否在一个文件中,申明和定义可以同时出现。我做了错误的反驳,特此说明。
例子:
test.h:
typedef struct
{
int a;
char b[12];
} test;
extern test *t;
***********************************************************************
test.c:
#include ;
#include ;
#include "test.h"
test *t;
int main()
{
t = (test *)malloc(sizeof(test));
t->;a = 2;
strcpy(t->;b,"abc");
test_func();
free(t);
return 0;
}
************************************************************************
test_func.c:
#include ;
#include "test.h"
void test_func()
{
printf("t->;b = %s/n",t->;b);
}
外部文件调用结构体变量
最新推荐文章于 2024-08-01 08:59:58 发布