外部文件调用结构体变量

//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);

}


  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值