最近遇到了一個問題,就是一個標頭檔有一個static的變數,編譯的檔案有幾個.o的,他們都引用了這個標頭檔,但是當列印出這個變數(經過修改了)的值得時候,居然不一樣,列印出地址來,地址居然也不一樣。兩個不同地址,一個相同的變數名?究竟怎麼回事情呢???
這個變數許多檔案要用。但是放到h檔案,又是個問題啊。。。
使用extern 聲明外部變數,必須符合下面的情況
產生的.o 不能引用包括這個變數定義的檔案。但是我又使用了這個標頭檔的其他函數,鬱悶了。
經過實驗 應是這樣的,變數 不要用static,因為外部要extern使用,反而不能用static了 才鬱悶呢。
實驗如下:
head1.h
#include <stdio.h>
extern int str_i;
head1.c
#include "head1.h"
int str_j=5;
int main(){
printf("str_i=%d\n",str_i);
func();
printf("str_i=%d\n",str_i);
}
head2.h
#include <stdio.h>
extern int str_j;
int str_i=1;
void func();
head2.c
#include "head2.h"
void func(){
str_i=999;
printf("str_j=%d\n",++str_j);
}
編譯方法為:
gcc -c head1.c
gcc -c head2.c
gcc -o main head1.o head2.o
或者
gcc -c head2.c
gcc -o main head1.c head2.o
結果如下:
$ ./main
str_i=1
str_j=6
str_i=999
head2 要使用的資源使用了
head1 要使用的資源也使用了。
但是head1不能使用head2的標頭檔,否則重複定義。
head2也不能使用head1的標頭檔,否則重複定義。
看來 使用 別人的東西,不一定要加 標頭檔的。函式宣告 也沒必要,只要在GCC中有對應的。o或lib就可以了。