extern報錯:static declaration follows non-static declaration

上一篇博客複習與回顧了extern的用法與知識點,於是參考<C和指針>第三章習題P49的第24題,發現課後答案與我自己在ubuntu上做的實驗有衝突,記錄下來

我把課後答案簡化了一下,貼上代碼

按照<C和指針課後答案>的說法,我的代碼第7行與第14行的y分屬不同作用域,所以是沒有問題的,<C和指針>代碼如下:

但是實實在在我們在ubuntu上看到了編譯錯誤,正確的改法應該將第3行的註釋去掉,將第14行註釋掉,結果請見最後

root@ubuntu:/lianxi/lianxi_oj/extern/exception# gcc func.c main.c -m32
main.c:14:1: 錯誤: 對‘y’的靜態聲明出現在非靜態聲明之後
main.c:7:13: 附註: ‘y’的上一個聲明在此
root@ubuntu:/lianxi/lianxi_oj/extern/exception# 
  1 #include <stdio.h>
  2 #define PRINT(fmt...) printf(fmt)
  3 int y = 10;
  4 void func3(void)
  5 {   
  6     PRINT("[func3]&y = %p\n", &y);
  7     PRINT("[func3]y = %d\n", y);
  8     return;
  9 }
  1 #include <stdio.h>
  2 #define PRINT(fmt...) printf(fmt)
  3 //static int y;
  4 void func1(void)
  5 {   
  6     /*non-static declaration*/
  7     extern int y;
  8     PRINT("[func1]&y = %p\n", &y);
  9     PRINT("[func1]y = %d\n", y);
 10     return;
 11 }
 12 
 13 /*static declaration*/
 14 static int y;//error:static declaration follows non-static declaration
 15 
 16 void func2(void)
 17 {   
 18     extern int y;
 19     PRINT("[func2]&y = %p\n", &y);
 20     PRINT("[func2]y = %d\n", y);
 21     return;
 22 }
 23 
 24 int main(int argc, char* argv[])
 25 {   
 26     func3();
 27     func1();
 28     func2();
 29     return 0;
 30 }

改正後的結果(沒有貼改正後的代碼)

root@ubuntu:/lianxi/lianxi_oj/extern/exception# gcc func.c main.c -m32
root@ubuntu:/lianxi/lianxi_oj/extern/exception# ./a.out
[func3]&y = 0x804a014
[func3]y = 10
[func1]&y = 0x804a020
[func1]y = 0
[func2]&y = 0x804a020
[func2]y = 0
root@ubuntu:/lianxi/lianxi_oj/extern/exception# 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章