2012-06-05 52 views
0

比方說,我有一個全局變量通過一個全局變量在一個C文件到另一個

char Dir[80]; /* declared and defined in file1.c but not exported using extern etc */ 

的dir變量是在運行時創建的目錄的名稱程序的main()。 在這個文件中,我們處理這個變量,並將它傳遞給在file2.c中定義的函數func。這個Dir變量是一個目錄,其中所有函數創建它們各自的日誌。

而不是將這個變量傳遞n次到每個最後調用func()的函數,我把它變成了全局變量。

func(x,Dir); /* x is a local variable in a function */ 

/*現在在file2.c中*/

void func(int x,char *Dir) 
{ 
    /*use this variable Dir */ 
} 

我們這裏收到的迪爾的價值是不一樣的file1.c中。爲什麼? 編譯器:在Windows上的gcc

+2

這可能是不同的,因爲你期待'Dir2'而不是'Dir'? –

+0

@MikeKwan這是一個複製粘貼錯誤,但我已經糾正它 – user1437565

+1

那麼代碼本身就很好。你能展示一個能夠再現你的問題的最小例子嗎? –

回答

4

你的代碼是好的,因爲它代表。我可以給你一個例子,說明如何在C中使用多個源文件,並且可以與你寫的內容進行比較。

給定一個main.c和含有func,需要定義一個some_lib.h其限定在some_lib.c定義的func函數原型一個some_lib.c

main.c

#include <stdlib.h> 
#include <stdio.h> 
#include "some_lib.h" 
/* 
* This means main.c can expect the functions exported in some_lib.h 
* to be exposed by some source it will later be linked against. 
*/ 

int main(void) 
{ 
    char dir[] = "some_string"; 

    func(100, dir); 
    return EXIT_SUCCESS; 
} 

some_lib.c(包含func定義):

#include "some_lib.h" 

void func(int x, char * dir) 
{ 
    printf("Received %d and %s\n", x, dir); 
} 

some_lib.h(包含的some_lib.c導出的函數的函數原型/聲明):

#ifndef SOME_LIB_H 
#define SOME_LIB_H 
#include <stdio.h> 

void func(int x, char * dir); 

#endif 

上述然後應該編譯:

gcc main.c some_lib.c -o main 

這將產生:

Received 100 and some_string 

不過,如果你確實使用全局變量,它甚至沒有必要通過dir在所有。考慮這個修改main.c

#include <stdlib.h> 
#include <stdio.h> 
#include "some_lib.h" 

char dir[] = "some_string"; 

int main(void) 
{ 
    func(100); 
    return EXIT_SUCCESS; 
} 

dir在這裏定義,是全球訪問/定義。我們所需要做的就是確保some_lib.c知道它存在。鏈接器可以在鏈接階段解析這個符號。需要some_lib.h被作爲這樣定義的:然後

#ifndef SOME_LIB_H 
#define SOME_LIB_H 
#include <stdio.h> 

/* 
* The extern informs the compiler that there is a variable of type char array which 
* is defined somewhere elsewhere but it doesn't know where. The linker will 
* match this with the actual definition in main.c in the linking stage. 
*/ 
extern char dir[]; 
void func(int x); 

#endif 

some_lib.c可以使用全局定義的變量,如同其在作用域:

#include "some_lib.h" 

void func(int x) 
{ 
    printf("Received %d and %s\n", x, dir); 
} 

編譯和運行,這將產生輸出作爲與第一實施例相同。

+0

需要注意的是,帶dir作爲本地的示例1是很好的編程實踐,而帶dir作爲全局的示例2是非常糟糕的編程實踐。 – Lundin

+0

有關全局變量的更多信息,請參閱此處:http://stackoverflow.com/questions/176118/when-is-it-ok-to-use-a-global-variable-in-c。 –

+0

我已經編程了C的年齡,從實時嵌入式系統到PC圖形絨毛。我有_never_需要使用全局變量。根據我的經驗,對全局變量的需求來自:1)泥濘的思維,和/或2)糟糕的程序設計,和/或3)對C語言的瞭解不足:不瞭解靜態變量,內聯和不透明數據類型(指向私有封裝的不完整類型的指針)。 – Lundin

相關問題