[問題] C static variable in shared library

看板C_and_CPP (C/C++)作者 (自我判斷 永保平靜)時間13年前 (2012/07/02 13:17), 編輯推噓2(203)
留言5則, 4人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) GCC 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 在library中宣告static variable StaticInt 在main.c中用staticInt++沒有效果 預期的正確結果(Expected Output): 1 2 3 4 錯誤結果(Wrong Output): 1 1 1 1 程式碼(Code):(請善用置底文網頁, 記得排版) // variable.h #include<stdio.h> static int staticInt = 1; void printStatic(); ----------------------------- // variable.c #incdlue<stdio.h> #include "variable.h" void printStatic(){ printf("staticInt = %d\n",staticInt); return; } ------------------------------ // main.c #include<stdio.h> #include "variable.h" int main(){ printStatic(); staticInt++; printStatic(); staticInt++; printStatic(); staticInt++; printStatic(); return 0; } 麻煩各位大大 幫我看一下為什麼staticInt++ 不會加到staticInt 我的想法裡 staticInt 的scope是宣告在library裡的 所以scope應該在main中可以access到 請問問題再哪~ 謝謝各位! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.90.49

07/02 13:20, , 1F
global static 是每個檔案各自有自己的一份
07/02 13:20, 1F

07/02 13:21, , 2F
你需要的是 extern
07/02 13:21, 2F

07/02 15:05, , 3F
推樓上global / global static有微妙的差別
07/02 15:05, 3F

07/02 15:16, , 4F
基本上把 static 寫在 header 就很有問題了吧 XD
07/02 15:16, 4F

07/02 16:43, , 5F
你可能要記一下static的三個用法...
07/02 16:43, 5F
文章代碼(AID): #1FyIx-Ac (C_and_CPP)
文章代碼(AID): #1FyIx-Ac (C_and_CPP)