2011-02-26 38 views
33

我想在兩個單獨的.c文件中編寫我的C函數,並使用我的IDE(代碼塊)將所有內容一起編譯。如何將C程序拆分爲多個文件?

如何在代碼塊中設置?

如何從另一個文件中的一個.c文件中調用函數?

+0

你是什麼IDE? – Simon

+3

我不明白這可能會有什麼模糊之處。你有沒有嘗試過任何東西?你知道C語言嗎?你知道標題是什麼嗎? –

+6

關於你沒有意識到這一點的可能性:通常在編譯c時,在討論*「調用[文件]以使用它們」時,*具有解釋性語言的感覺。編譯語言的工作流程與解釋語言的工作流程略有不同(儘管許多IDE將隱藏與您的區別)。 – dmckee

回答

88

這個問題非常模糊,我想你的意思是「如何分開各種.c文件中的函數並讓IDE一起編譯所有東西」。如果我錯了(例如,您的意思是「如何使用IDE中定義的.c文件中的函數」),請在評論中告訴我,我很樂意更新/刪除我的答案。

在一般情況下,你應該定義在兩個單獨的.c文件(比如,A.cB.c)的功能,並把他們的原型在相應的頭文件(A.hB.h,記得include guards)。

無論何時在.c文件中您需要使用另一個.c中定義的函數,您將在#include的對應標題;那麼你將能夠正常使用這些功能。

所有.c.h文件必須添加到您的項目;如果IDE詢問你是否需要編譯,你應該只標記.c進行編譯。

快速例如:

Functions.h

#ifndef FUNCTIONS_H_INCLUDED 
#define FUNCTIONS_H_INCLUDED 
/* ^^ these are the include guards */ 

/* Prototypes for the functions */ 
/* Sums two ints */ 
int Sum(int a, int b); 

#endif 

Functions.c

/* In general it's good to include also the header of the current .c, 
    to avoid repeating the prototypes */ 
#include "Functions.h" 

int Sum(int a, int b) 
{ 
    return a+b; 
} 

MAIN.C

#include "stdio.h" 
/* To use the functions defined in Functions.c I need to #include Functions.h */ 
#include "Functions.h" 

int main(void) 
{ 
    int a, b; 
    printf("Insert two numbers: "); 
    if(scanf("%d %d", &a, &b)!=2) 
    { 
     fputs("Invalid input", stderr); 
     return 1; 
    } 
    printf("%d + %d = %d", a, b, Sum(a, b)); 
    return 0; 
} 
+0

我使用的代碼塊 – amin

+0

是的,你是對的 – amin

+0

如果我想使用.c文件,我應該使它的頭文件(.h)呢! – amin

相關問題