C語言零碎記錄之extern

來源:互聯網
上載者:User

最近遇到了一個問題,就是一個標頭檔有一個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就可以了。

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.