extern声明外部结构体

发布 2019-07-06 06:04:15 阅读 1724

在extern声明外部结构体变量时,遇到问题如下:

文件。struct struct_plc_mdl_productinfo versiondate路由模块版本日期。

uint16 versionid路由模块版本号。

uint8 comtype路由模块通信方式。

uint8 ch_num路由模块信道个数。

uint8 productid[6路由模块生产编号。

uint8 str_pmtype[10路由模块类型型号(ascii码)

uint8 str_productdate[10路由模块生产日期(ascii码)

uint8 str_pmcopyright[32路由模块版本信息(ascii码)

uint8 str_pmmanufacturer [32]; 路由模块厂商信息(ascii码)

const struct struct_plc_mdl_productinfo plc_mdl_productinfo = 0x0000, 0x02, 0x01, \plr-m1.0 ",2011-02-10",

"路由模块版本信息",

"路由模块厂商信息" }

文件。extern const struct struct_plc_mdl_productinfo plc_mdl_productinfo;

文件。#include “

uint16 a;

a = plc_mdl_productinfo. modelid;

编译出错,提示文件中的plc_mdl_productinfo必须是一个结构体或者共用体。

于是就很困惑:按之前的了解,extent声明外部变量不都是这样写的吗,直接声明就行了,在中声明变量plc_mdl_productinfo,然后在中包含头文件不就可以用变量plc_mdl_productinfo了吗?然而这里确报错了。

最后,经过询问别人,查询资料,知晓大概原因:之前的extern声明变量遇到的都是基本类型的外部变量,然而这里确是声明的外部变量却是构造类型(结构体)类型。问题就出在这里。

中虽然声明了结构体变量plc_mdl_productinfo,但是却没有该结构体的定义实体,所以编译器就报错了。

于是改动如下:

文件。#include “

const struct struct_plc_mdl_productinfo plc_mdl_productinfo = 0x0000, 0x02, 0x01, \plr-m1.0 ",2011-02-10",

"路由模块版本信息",

"路由模块厂商信息" }

文件 struct struct_plc_mdl_productinfo versiondate路由模块版本日期。

uint16 versionid路由模块版本号。

uint8 comtype路由模块通信方式。

uint8 ch_num路由模块信道个数。

uint8 productid[6路由模块生产编号。

uint8 str_pmtype[10路由模块类型型号(ascii码)

uint8 str_productdate[10路由模块生产日期(ascii码)

uint8 str_pmcopyright[32路由模块版本信息(ascii码)

uint8 str_pmmanufacturer [32]; 路由模块厂商信息(ascii码)

extern const struct struct_plc_mdl_productinfo plc_mdl_productinfo;

文件。#include “

uint16 a;

a = plc_mdl_productinfo. modelid;

将中结构体struct struct_plc_mdl_productinfo的定义放到中,自然中就要加一句#include “否则就没法定义变量plc_mdl_productinfo了。

然后编译,就没有错误了。

但是依然有疑惑,把结构体定义的实体放到中,然后声明外部变量plc_mdl_productinfo,这肯定就没错了。但是,我们知道声明基本类型的外部变量时,如extern int a;可以省略变量类型,直接写为extern a;。于是我就把中的变量声明写成extern plc_mdl_productinfo;,编译就出错了,提示文件中的plc_mdl_productinfo必须是一个结构体或者共用体。

看来是不能省略变量类型了。

因此,对于声明外部构造类型(结构体,共用体)变量,要注意两点,这两点也是和声明外部基本类型变量的区别。

一、声明外部构造类型变量时,该文件中必须要有构造类型的定义实体,否则会报错。

二、声明外部构造类型变量时,不能省略变量类型,否则也会报错。(声明外部基本类型变量时,却可以省略变量类型)。

这是我个人分析得出的结论,至于编译器为什么会这样处理,有待进一步的了解。