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;
}

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/18855397ac.html