我的1.c
float e;
void f1(){ e=3.0;}
我的2.c
#include <stdio.h>
int e=0;
void f1();
void main(){
printf("%d in main \n", e);
f1();
printf("%d in main \n", e);
}
這里全域變數e被錯誤地宣告為float和int在兩個源檔案中。
如何讓聯結器為這種不一致引發錯誤?
uj5u.com熱心網友回復:
我們使用頭檔案而不是聯結器來減輕這種風險。在多個翻譯單元中參考的任何內容都應在一個頭檔案中宣告:
我的全球.h:
extern float e;
任何使用它的檔案都應該包含頭檔案:
主.c:
#include "MyGlobal.h"
…
printf("e is %f.\n", e);
只需要一個檔案來定義它,并包含頭檔案:
我的全球.c:
#include "MyGlobal.h"
float e = 0;
通過使用頭檔案,所有翻譯單元中的宣告都是相同的。因為定義識別符號的源檔案還包括頭檔案,所以編譯器會報告任何不一致。
頭檔案之外的任何外部宣告(不是定義)都是可疑的,應該避免。
uj5u.com熱心網友回復:
1.c
static float e;
void f1(){ e=3.0;}
2.c
#include <stdio.h>
static int e=0;
void f1();
void main()
{
printf("%d in main \n", e);
f1();
printf("%d in main \n", e);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/434825.html
上一篇:隨機序列在c中看起來不是隨機的
下一篇:將字符一一添加到二維字符陣列
