2014-12-04 36 views
1

嗨StackOverflow的巫師使用的extern變量:在多個C文件

我有以下三個簡單的C文件:

// File 1 
#include "mainPgm.h" 
void file1() { 
    printf("N1 is now %d.\n", n1);      
} 

// File 2 
#include "mainPgm.h" 
void file2() { 
    printf("N2 is now %d.\n", n2);      
} 

// File 3 
#include "mainPgm.h" 
void file3() { 
    printf("N3 is now %d.\n", n3);      
} 

,當然主要程序:

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

int main() { 
    int n1 = 65536, 
     n2 = 256, 
     n3 = 16; 

    file1(); 
    file2(); 
    file3(); 
} 

最後,一個頭文件:

#include<stdio.h> 
void file1(), file2(), file3(); 
extern int n1, n2, n3; 

所有這些都是編譯一個簡單的gcc命令:

gcc -std=gnu99 -O2 -o jj -Wunused file1.c file2.c file3.c mainPgm.c 

這將導致以下錯誤:

mainPgm.c: In function ‘main’: 
mainPgm.c:8:7: warning: unused variable ‘n3’ [-Wunused-variable] 
mainPgm.c:7:7: warning: unused variable ‘n2’ [-Wunused-variable] 
mainPgm.c:6:7: warning: unused variable ‘n1’ [-Wunused-variable] 
/tmp/ccVQjFHY.o: In function `file1': 
file1.c:(.text+0x2): undefined reference to `n1' 
/tmp/ccZqyI0n.o: In function `file2': 
file2.c:(.text+0x2): undefined reference to `n2' 
/tmp/ccbpJOpN.o: In function `file3': 
file3.c:(.text+0x2): undefined reference to `n3' 
collect2: error: ld returned 1 exit status 

認爲是定義在mainPgm.h N1,N2和N3會用於聲明變量,並且它們在mainPgm.c中的定義將定義它們。沒有!我哪裏做錯了?

TIA!

+0

參見[如何使用'extern'共享源文件之間的變量C4](http://stackoverflow.com/questions/1433204/how-do-i-use-extern-to-share-variables -between - 源文件 - 在-C/1433387#1433387) – 2014-12-04 16:12:53

+0

你可能(也可能不會)護理需要注意的是:(1)你的主要程序不從''或''(所以那些使用任何代碼包括是不必要的); (2)頭'「mainPgm.h」'並不需要包括''如沒有聲明它依賴於任何聲明,從'' - 但是如果你刪除''從'「mainPgm.h 「',你需要在每個'fileN.c'文件中明確包含''。在'mainPgm.c'文件中,你實際上包含了''兩次。這是無害的;標準的C頭文件是獨立的和冪等的。你的標題也應該是。 – 2014-12-04 16:18:02

+0

我從mainPgm.c中刪除了stdio和stdlib聲明,並沒有編譯問題。 – Boffin 2014-12-04 17:24:33

回答

3

您的變量的所有都在裏面main()局部變量,他們將永遠不會從該函數外可見。

移出來,使他們的全球:

int n1 = 65536, 
     n2 = 256, 
     n3 = 16; 

int main() { 
    file1(); 
    file2(); 
    file3(); 

    return EXIT_SUCCESS; 
} 
+0

這是問題的核心,程序現在起作用。謝謝! – Boffin 2014-12-04 17:21:13

2

你在你的main()函數中定義的變量,在堆棧中。

您可以在同一個文件中定義它們,但不在主函數之外。

另外一個常見的C成語是使用預處理器聲明變量爲外部,但在所有你的頭文件的一個實例。