看板 C_and_CPP 關於我們 聯絡資訊
Online GDB 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) GCC 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) None 問題(Question): 使用test.i 出現錯誤 餵入的資料(Input): None 預期的正確結果(Expected Output): test.i=1 錯誤結果(Wrong Output): error: invalid use of undefined type 'struct A' 程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔) main.c extern struct DATA test; int main() { test.i=1; return 0; } test.c struct DATA { int i; }; struct DATA test={0}; 補充說明(Supplement): None
wulouise: main.c怎麼知道你在test.c declare DATA?03/01 23:16
我原本以為只要test.c有delcare 後compile 在link 的時候就可以讓main.c去extern stru ct DATA且使用,看來這是錯誤的理解。 也就是說我必須也要在main.c中delcare struct DATA,讓main.c知道有這個delcare,這時 候extern 才可以知道這個test變數的型態是struct DATA。 這要理解不知道有沒有問題。如有問題還請大大多指點。謝謝! ※ 編輯: OnlyCourage (114.36.205.245 臺灣), 03/01/2024 23:37:09
lc85301: 你怎麼把文修成這個樣子…03/01 23:42
OnlyCourage: 靠..我能恢復嗎..還是只能刪掉重發..03/01 23:59
OnlyCourage: 抱歉03/01 23:59
※ 編輯: OnlyCourage (114.36.205.245 臺灣), 03/02/2024 00:03:33 ※ 編輯: OnlyCourage (114.36.205.245 臺灣), 03/02/2024 00:09:54
OnlyCourage: 我已經儘量恢復了 不好意思 03/02 00:10
※ 編輯: OnlyCourage (114.36.205.245 臺灣), 03/02/2024 00:11:07
tinlans: C 語言的 struct definition 不會被編譯到 object file 03/02 03:45
tinlans: 裡面去,所以在 linking time 完全遺失這項資訊。 03/02 03:45
tinlans: 但你的問題主要不在於這件事上,而是你在 main.c 沒有告 03/02 03:47
tinlans: 知 compiler 說 DATA 這個 identifier 是什麼東西,缺乏 03/02 03:47
tinlans: 了 DATA 的 declaration。 03/02 03:48
tinlans: 又因為你在 main.c 嘗試存取 test.i 也就是 DATA 的成員 03/02 03:49
tinlans: ,此處需要 DATA 的 definition,否則 compiler 不知道 i 03/02 03:50
tinlans: 的 type 以及它的 address offset 是多少,所以報錯。 03/02 03:51
tinlans: 你遇到的問題不是 linking-time error 而是 compile-time 03/02 03:55
tinlans: error,所以一開始的思路就錯了,有些基礎需要重新加強。 03/02 03:55
tinlans: 宣告(declaration)和定義(definition)這兩個詞彙也得好好 03/02 03:57
tinlans: 重新理解,找不到適當的文章的話,問看看 ChatGPT。 03/02 03:57
tinlans: 另外,你對 extern 這個關鍵字的理解也有問題,它修飾的 03/02 04:04
tinlans: 對象是 test 不是 struct DATA test 整段,也不是 struct 03/02 04:04
tinlans: DATA,這只是告訴 compiler 說 test 被 define 在別處。 03/02 04:05
OnlyCourage: 大概懂意思了,謝謝兩位大大的指教,我會再去多鑽研 03/03 14:35
OnlyCourage: 。感謝~~ 03/03 14:35