簡體   English   中英

為什么在已定義函數的源代碼中添加頭文件?

[英]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采用inthello_fn.c認為采用C字符串。

我在運行時得到核心轉儲(1) ,因為值42不是有效的字符串地址。 當我取消注釋hello_fn.cinclude hello_fn.c ,編譯器會(正確地)抱怨我的聲明和定義不同意(因為hello_fn.c/hello.h對現在不一致)。


最重要的是,標頭中可能存在僅存在於標頭中的其他內容(盡管在您的示例中不是)。 這通常是在調用方和被調用方之間共享的聲明,例如類型, extern項目,# #define項目等。 在頭文件和源文件中分別聲明它們幾乎沒有意義。


(1) 實際結果可能會有所不同,因為這是不確定的行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM