variable `xxx‘ has initializer but incomplete type 错误分析及解决办法

一、错误提示

编译时报错:
variable `xxx’ has initializer but incomplete type

二、产生原因及解决办法

在编译某一个文件时,对变量进行了初始化,但是在初始化之前,没有定义过这个变量,只是声明过。
初始化、声明、定义,这几个的不同一定要清楚。
举个浅显的例子:

struct myStruct; // Declaration of myStruct, but not its definition

int main() {
    struct myStruct x = {0, 1, 2}; // Initialization of x with an incomplete type
    return 0;
}

struct myStruct {
    int a, b, c;
};

在这个例子当中,当你编译的时候,先编译main(),但是却在main()函数之后对 myStruct这个结构体进行了定义,编译将会报错。

修复错误的方法是,在初始化之前,对结构体变量的类型进行完全定义。或者是将这个定义放在main()函数之前,或者是将这个定义的部分写在.h文件中,将这个.h文件,在头部包含进去。(本例子是为了解释原理,实际编程时请注意规范)
修改方法一:

struct myStruct {
    int a, b, c;
};

int main() {
    struct myStruct x = {1, 2, 3}; // Initialization of x with a complete type
    return 0;
}

修改方法二:
struct.h文件如下:

#ifndef _STRUCT_H_
#define _STRUCT_H_

struct myStruct {//definition a complete type 
    int a, b, c;
};

#endif

使用时:

#include "struct.h"//include the .h file where myStruct initialization

int main() {
    struct myStruct x = {1, 2, 3}; // Initialization of x with a complete type
    return 0;
}
  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值