一、錯(cuò)誤提示
編譯時(shí)報(bào)錯(cuò):
variable `xxx’ has initializer but incomplete type
二、產(chǎn)生原因及解決辦法
在編譯某一個(gè)文件時(shí),對(duì)變量進(jìn)行了初始化,但是在初始化之前,沒有定義過這個(gè)變量,只是聲明過。
初始化、聲明、定義,這幾個(gè)的不同一定要清楚。
舉個(gè)淺顯的例子:
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;
};
在這個(gè)例子當(dāng)中,當(dāng)你編譯的時(shí)候,先編譯main(),但是卻在main()函數(shù)之后對(duì) myStruct這個(gè)結(jié)構(gòu)體進(jìn)行了定義,編譯將會(huì)報(bào)錯(cuò)。
修復(fù)錯(cuò)誤的方法是,在初始化之前,對(duì)結(jié)構(gòu)體變量的類型進(jìn)行完全定義?;蛘呤菍⑦@個(gè)定義放在main()函數(shù)之前,或者是將這個(gè)定義的部分寫在.h文件中,將這個(gè).h文件,在頭部包含進(jìn)去。(本例子是為了解釋原理,實(shí)際編程時(shí)請(qǐng)注意規(guī)范)
修改方法一:
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文件如下:文章來源:http://www.zghlxwxcb.cn/news/detail-514799.html
#ifndef _STRUCT_H_
#define _STRUCT_H_
struct myStruct {//definition a complete type
int a, b, c;
};
#endif
使用時(shí):文章來源地址http://www.zghlxwxcb.cn/news/detail-514799.html
#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;
}
到了這里,關(guān)于variable `xxx‘ has initializer but incomplete type 錯(cuò)誤分析及解決辦法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!