開發平台(Platform)(Ex: Win10, Linux, ...)
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
1F:→ 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
2F:推 lc85301: 你怎麼把文修成這個樣子…03/01 23:42
3F:→ OnlyCourage: 靠..我能恢復嗎..還是只能刪掉重發..03/01 23:59
4F:→ 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
5F:→ OnlyCourage: 我已經儘量恢復了 不好意思 03/02 00:10
※ 編輯: OnlyCourage (114.36.205.245 臺灣), 03/02/2024 00:11:07
6F:→ tinlans: C 語言的 struct definition 不會被編譯到 object file 03/02 03:45
7F:→ tinlans: 裡面去,所以在 linking time 完全遺失這項資訊。 03/02 03:45
8F:→ tinlans: 但你的問題主要不在於這件事上,而是你在 main.c 沒有告 03/02 03:47
9F:→ tinlans: 知 compiler 說 DATA 這個 identifier 是什麼東西,缺乏 03/02 03:47
10F:→ tinlans: 了 DATA 的 declaration。 03/02 03:48
11F:→ tinlans: 又因為你在 main.c 嘗試存取 test.i 也就是 DATA 的成員 03/02 03:49
12F:→ tinlans: ,此處需要 DATA 的 definition,否則 compiler 不知道 i 03/02 03:50
13F:→ tinlans: 的 type 以及它的 address offset 是多少,所以報錯。 03/02 03:51
14F:→ tinlans: 你遇到的問題不是 linking-time error 而是 compile-time 03/02 03:55
15F:→ tinlans: error,所以一開始的思路就錯了,有些基礎需要重新加強。 03/02 03:55
16F:→ tinlans: 宣告(declaration)和定義(definition)這兩個詞彙也得好好 03/02 03:57
17F:→ tinlans: 重新理解,找不到適當的文章的話,問看看 ChatGPT。 03/02 03:57
18F:→ tinlans: 另外,你對 extern 這個關鍵字的理解也有問題,它修飾的 03/02 04:04
19F:→ tinlans: 對象是 test 不是 struct DATA test 整段,也不是 struct 03/02 04:04
20F:→ tinlans: DATA,這只是告訴 compiler 說 test 被 define 在別處。 03/02 04:05
21F:→ OnlyCourage: 大概懂意思了,謝謝兩位大大的指教,我會再去多鑽研 03/03 14:35
22F:→ OnlyCourage: 。感謝~~ 03/03 14:35