到底是hello.c調用test.c的,還是test.c調用hello.c的函數
hello.c
#include <stdio.h>
#include "test.c" ? //引用test.c文件
extern void printLine() ? ? //這里定義的方法對嗎?
{
? ?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函數調用say函數,這個say函數是定義在test.c中的。本質上是函數間調用,與文件無關。程序永遠是從main函數開始運行的。
你這代碼中有很多錯誤和不合理之處:
不應該直接在代碼中include另一個函數定義文件,這樣做會將test.c中的內容都包含到hello.c中,所以實際上最后main和say函數都是定義在hello.c中的。
而且在test.c中,say函數調用了printLine函數,但在之前卻并沒有聲明printLine(聲明在hello.c中)。
聲明函數時不用寫extern,函數默認就是external的(準確地說是previous linkage)。
正確的做法是:
一般來說將函數的定義寫在某個.c文件中,將其聲明寫在.h中。函數在使用前需要函數聲明,所以將函數聲明(非定義)寫到一個.h文件中,稱為頭文件。在其他需要調用這個函數的文件中只需include這個頭文件就可以得到函數聲明了。如果像你代碼中那樣直接include進.c文件,就會把函數定義也包含進來,這樣可能造成程序中有多處該函數的定義,這是不合法的,編譯器會報重復定義錯誤。
2015-07-18
這個是hello.c調用test.c啊