2015-01-15 61 views
2

我有一個非常複雜的概念,當我編譯許多文件時會發生什麼 - 主要涉及到從一個文件到另一個文件的可見性。從我讀的內容來看,static將變量或函數的範圍限制在文件本身。 extern則相反。從那以後,我希望能夠從任何文件中簡單閱讀global extern。儘管如此,這在實踐中並不奏效。源文件中static/extern的用法是什麼?

的main.c:

#include <stdio.h> 

int main(void){ 
    printf("%d\n", b); // b is extern global 
    return 0; 
} 

交流轉換器:

static int a = 40; 

b.c:

extern int b = 20; 

我甚至無法編譯:

> gcc main.c a.c b.c -o test 
b.c:1:12: warning: ‘b’ initialized and declared ‘extern’ [enabled by default] 
extern int b = 20; 
      ^
main.c: In function ‘main’: 
main.c:4:20: error: ‘b’ undeclared (first use in this function) 
    printf("%d\n", b); // b is extern global 
+0

這site.Its這是在.h文件所有的extern變量,包括它們在需要.c文件 – Gopi 2015-01-15 18:03:38

回答

1

你錯了,當我們寫extern int b這意味着一個整型變量被稱爲b已被聲明。並且我們可以根據需要多次執行此聲明。 (請記住,聲明可以進行多次)。通過externing變量,我們可以在程序中的任何地方使用變量,只要我們知道它們的聲明並且變量是在某處定義的。

正確的方法是

的main.c:

#include <stdio.h> 

extern int b; //declaration of b 
int main(void){ 
    printf("%d\n", b); // using b 
    return 0; 
} 

b.c:

int b = 20; //definition here 

和編譯爲gcc main.c b.c -o test

我有省略了a.c,因爲它在這個例子中沒有做任何事情。 要了解更多關於實習醫生看到有很好的內容http://www.geeksforgeeks.org/understanding-extern-keyword-in-c/

+0

謝謝,這是最簡單的解釋:) – Pithikos 2015-01-15 18:27:33

+0

歡迎高興地幫助:) – Ankur 2015-01-15 18:28:10

+0

'extern int b;'爲什麼我們需要extern這裏默認情況下全局變量是extern – Gopi 2015-01-15 18:36:52

0

如果聲明或定義了變量,則可以使用該變量。

main.c中,沒有聲明b。您可以在main.c添加

extern int b; 

讓編譯器能夠使用b。這向編譯器聲明b是在其他地方定義的,它的類型爲int。您可以刪除extern這個詞。除非符合static,否則默認爲extern

int b = 20; 

即使在b.c,你可以在文件的頂部使用的聲明,並在底部定義它。

extern int b; 

// 
// ... code that uses b 
// 

int b = 20; 

extern行只是聲明變量。最後一行定義變量。

0

當你有一個extern變量時,編譯器知道這個變量的聲明在這裏,而定義在別的地方。

所以,你可以做如下圖所示

some.h

extern int b; /* Declare the variable */ 

b.c

int b = 20; /* Define the variable */ 

的main.c

#include<some.h> 

    int main() 
    { 
     printf("%d\n",b); /* Use the variable b */ 

     return 0; 
    } 

現在這個文件爲主。c知道b的聲明,因爲它存在some.h文件。

+0

包括some.h一個好主意,是沒有必要的我猜 – Ankur 2015-01-15 18:19:31

相關問題