2014-09-27 67 views
0

全球價值是不是在其他文件訪問?mycode的是下面請大家幫我解決全局值在另一個文件中無法訪問?

flie1.c

#include<stdio.h> 
extern int i=9; 
    int main() 
{ 
    printf("i m in main\n"); 
} 

file2.c中

printf("%d\n",i); 

我正在編制兩個文件一次as cc file1.c file2.c

+0

你得到了什麼錯誤? – Rustam 2014-09-27 17:11:41

+0

不要忘記閱讀本[回答](http://stackoverflow.com/a/1433387/2455888)(仔細)。 – haccks 2014-09-27 17:14:50

回答

0

像這樣改變它,它會工作:

file1.c中

#include <stdio.h> 
int i = 9; // define the variable 
void print(); // declare print: say there is a function called `print` with no arguments and no return type (because the function is DEFINED in file2.c) 

int main() { 
    printf("im in main"); 
    print(); 
    return 0; 
} 

file2.c中

extern int i; // declare "i": say there is a variable called `i` with type of `int` (because the variable is DEFINED in file1.c) 

void print() { 
    printf("%d\n", i); 
} 
0

當你有一個外部變量,它也應該有它的 '原始' 的聲明(不使用EXTERN)。 extern只是說'這個變量是在別處定義的',所以你需要在某處定義變量。

只需添加:

int i=9; 

到file2.c中(在文件中, '全局' 區域「的頂部)

,你可以改變你的外部聲明到:

extern int i; 

(沒有賦值9)在file1.c中