到底是hello.c調(diào)用test.c的,還是test.c調(diào)用hello.c的函數(shù)
hello.c
#include <stdio.h>
#include "test.c" ? //引用test.c文件
extern void printLine() ? ? //這里定義的方法對(duì)嗎?
{
? ?printf("**************\n"); ??
}
int main()
{
? ? say();
? ? return 0;
}
test.c
#include <stdio.h>
void say(){
? ? printLine();
? ? printf("I love imooc\n");
? ? printf("good good study!\n");
? ? printf("day day up!\n");
? ? printLine();
}?
2015-07-18
是hello.c中的main函數(shù)調(diào)用say函數(shù),這個(gè)say函數(shù)是定義在test.c中的。本質(zhì)上是函數(shù)間調(diào)用,與文件無(wú)關(guān)。程序永遠(yuǎn)是從main函數(shù)開始運(yùn)行的。
你這代碼中有很多錯(cuò)誤和不合理之處:
不應(yīng)該直接在代碼中include另一個(gè)函數(shù)定義文件,這樣做會(huì)將test.c中的內(nèi)容都包含到hello.c中,所以實(shí)際上最后main和say函數(shù)都是定義在hello.c中的。
而且在test.c中,say函數(shù)調(diào)用了printLine函數(shù),但在之前卻并沒有聲明printLine(聲明在hello.c中)。
聲明函數(shù)時(shí)不用寫extern,函數(shù)默認(rèn)就是external的(準(zhǔn)確地說(shuō)是previous linkage)。
正確的做法是:
一般來(lái)說(shuō)將函數(shù)的定義寫在某個(gè).c文件中,將其聲明寫在.h中。函數(shù)在使用前需要函數(shù)聲明,所以將函數(shù)聲明(非定義)寫到一個(gè).h文件中,稱為頭文件。在其他需要調(diào)用這個(gè)函數(shù)的文件中只需include這個(gè)頭文件就可以得到函數(shù)聲明了。如果像你代碼中那樣直接include進(jìn).c文件,就會(huì)把函數(shù)定義也包含進(jìn)來(lái),這樣可能造成程序中有多處該函數(shù)的定義,這是不合法的,編譯器會(huì)報(bào)重復(fù)定義錯(cuò)誤。
2015-07-18
這個(gè)是hello.c調(diào)用test.c啊