![](/img/trans.png)
[英]Extern variable in header file not linked properly to source file where it is defined
[英]Why a header file is added in the source code where the function is ALREADY defined?
例如,如果我用C編寫了以下三個文件:
你好
void hello (const char * name);
你好ç
#include "hello.h"
int
main (void)
{
hello ("world");
return 0;
}
hello_fn.c
#include <stdio.h>
#include "hello.h"
void
hello (const char * name)
{
printf ("Hello, %s!\n", name);
}
我知道將#include "hello.h"
到hello.c中告訴編譯器在外部文件(單獨編譯)期間將提供hello (const char * name)
的定義, 但是我現在的問題是為什么在hello_fn.c包含hello (const char * name)
的定義時將其添加到文件hello_fn.c中,我的意思是不會從外部提供它嗎?
謝謝
這實際上是一個好習慣,因為編譯器可以根據您的定義(在hello_fn.c
)檢查您的聲明(在標頭中)。
沒有這些,就無法確保它們匹配。 您可以很容易地提出:
void hello (int notCorrect) { ... }
放入您的C源文件中,它將很樂意獨立地編譯兩個源文件,然后(取決於您在...
位中實際執行的操作)在運行時會嚴重失敗。
例如,考慮以下文件:
hello.c:
#include <stdio.h>
#include "hello.h"
int main(void) { hello(42); }
hello_fn.c:
#include <stdio.h>
//#include "hello.h"
void hello(char *x) { puts(x); }
hello.h:
int hello(int x);
這樣編譯就可以了,因為每個C源文件的狀態在內部都是一致的。 hello.c/hello.h
對認為hello
采用int
而hello_fn.c
認為采用C字符串。
我在運行時得到核心轉儲(1) ,因為值42
不是有效的字符串地址。 當我取消注釋hello_fn.c
的include
hello_fn.c
,編譯器會(正確地)抱怨我的聲明和定義不同意(因為hello_fn.c/hello.h
對現在不一致)。
最重要的是,標頭中可能存在僅存在於標頭中的其他內容(盡管在您的示例中不是)。 這通常是在調用方和被調用方之間共享的聲明,例如類型, extern
項目,# #define
項目等。 在頭文件和源文件中分別聲明它們幾乎沒有意義。
(1) 實際結果可能會有所不同,因為這是不確定的行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.