之前一直很糾結c語言的重複定義的問題,並且因此吃過虧。
今天,石輔寸來分享一下怎樣的重複聲明是錯誤的,哪些重複聲明是允許的。
此文完全是筆者自己試驗的結果,如果有不對的地方希望大家補充,批評,共同進步。
全文的總結論:所有變量和函數都可以重複聲明,但是不能再頭文件中定義。
分析如下。
0,什麽是聲明與定義
0.1,變量
int a;//聲明整型變量a
a = 1;//定義a的值
int b = 1;//聲明并定義b
0.2,函數
int a();//聲明函數a
int a()//定義函數
{
printf("hello dear!");
}
1,在頭文件中聲明函數和變量
定義一個頭文件"text.h":
頭文件"text.h"
#include<stdio.h>
int a;
int b;
int text();
int text1();
int text2();
定義其他函數:
#include"text.h"
int main()
{
text1();
text2();
text();
}
#include"text.h"
int text()
{
printf("%d\n",a);
printf("%d\n",b);
return 0;
}
#include"text.h"
int text1()
{
printf("%d\n",a);
printf("%d\n",b);
return 0;
}
#include"text.h"
int text2()
{
printf("%d\n",a);
printf("%d\n",b);
return 0;
}
運行結果:
編譯情況:0錯誤0警告
結論:c語言允許在頭文件中聲明函數與變量的原型。
2,在頭文件中定義函數或變量。
1,頭文件中聲明變量,且同時定義變量a,其他c文件不變。
頭文件"text.h"
#include<stdio.h>
int a = 100;
int b;
int text();
int text1();
int text2();
運行結果:
出現鏈接錯誤,之前我查“ld returned 1 exit status”的時候,什麽奇奇怪怪的解釋都有,當你在頭文件中定義(為變量賦值)了而不僅僅是聲明的時候,就有可能報這個錯誤。
結論:頭文件中不能為定義變量。
2,頭文件中定義函數
在函數text后加上函數體,其它文件不變
頭文件"text.h"
#include<stdio.h>
int a;
int b;
int text()
{
printf("%d\n",a);
printf("%d\n",b);
return 0;
}
int text1();
int text2();
運行結果:錯誤,text重複定義
分析:當你在頭文件中引入函數定義的時,又把這個頭文件引入到其它c文件中,相當於把這個函數在這些c文件中都寫了一遍,當這個函數需要被調用的時候,計算機不知道應該打開那個c文件,所以必然出錯。
結論:頭文件中不能定義函數。
3,在頭文件中聲明數組或指針。
3.1,頭文件中把a聲明為指針。
頭文件"text.h"
#include<stdio.h>
int *a;
int b;
int text();
int text1();
int text2();
子函數輸出做出相應改變。
#include"text.h"
int text()
{
a = &b;
printf("%d\n",*a);
printf("%d\n",b);
return 0;
}
運行結果:
0錯誤0警告
結論:指針可以在頭文件中聲明。
在頭文件中定義指針。
頭文件改成:
#include<stdio.h>
int b;
int *a = &b;
int text();
int text1();
int text2();
子函數改成:
#include"text.h"
int text()
{
printf("%d\n",*a);
printf("%d\n",b);
return 0;
}
運行結果:編譯失敗
出現了“ld returned 1 exit status”的錯誤提示。
結論:指針不能再頭文件中定義。
3.2,頭文件中把a聲明為數組。
頭文件改成:
#include<stdio.h>
int a[5];
int b;
int text();
int text1();
int text2();
子函數改成:
#include"text.h"
int text()
{
printf("%d\n",*a);
printf("%d\n",b);
return 0;
}
運行結果:
0錯誤0警告。
結論:數組可以在頭文件中聲明。
在頭文件中定義數組。
#include<stdio.h>
int a[5] = 0;
int b;
int text();
int text1();
int text2();
#include"text.h"
int text()
{
printf("%d\n",*a);
printf("%d\n",b);
return 0;
}
運行結果:
報錯:無效的初始化。
結論:頭文件中不能定義數組。
綜上,所有變量和函數都可以重複聲明,但是不能再頭文件中定義。