Re: [問題] extern "C"的問題

看板C_and_CPP (C/C++)作者 (我愛阿蓉)時間16年前 (2009/06/10 13:46), 編輯推噓8(8017)
留言25則, 3人參與, 最新討論串3/5 (看更多)
不好意思 我現在自己想問題測試 其實我對extern "C"真的不是很懂 z大說的我明白 而我現在寫法是這樣如下 main.cpp #include <iostream> using namespace std; #include "test.h" int main() { foo2(); system("PAUSE"); return 0; } test.c #include <stdlib.h> #include <stdio.h> typedef struct FF{ int a; int b; }FU; void foo(){ printf("@@"); } FU* foo2() { FU* p=(FU*)malloc(sizeof(FU)); printf("FU"); return p; } test.h #ifndef _TEST_H #define _TEST_H #include <stdlib.h> #include <stdio.h> extern "C" { struct FU; void foo(); FU* foo2(); } #endif 以上這樣寫 是為了讓 test.c不去include test.h(我那個struct .c必須用到) 這樣可以compile過 但是我繼續想辦法try 我將extern "C"拿掉 test.c改成test.cpp 竟然就認不到了........... 原因很想請板上高手解釋一下 因為我知道struct改成class的話 上面的改法 就不會有問題 1.為什麼struct卻不能呢? 2.一開始我這樣故意把.c的include .h拿掉是不是一個好的作法? 不然勢必extern "C"就要寫在main ==>extern "C"{include "test.h"} 很抱歉問題有點多 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.113.207.187

06/10 13:48, , 1F
應該是 typedef 不能吧...
06/10 13:48, 1F

06/10 13:50, , 2F
如果你不喜歡在main.cpp放extern "C"那可以學stdio.h的作法
06/10 13:50, 2F

06/10 13:50, , 3F
我拿掉typedef 可以過了?但是 原因差別在哪呢@@
06/10 13:50, 3F

06/10 13:50, , 4F
#ifdef __cplusplus (詳細的你google吧,推文不好講)
06/10 13:50, 4F

06/10 13:51, , 5F
這樣做就可以像stdio.h一樣,不管是C或C++去include該檔都沒ok
06/10 13:51, 5F

06/10 13:51, , 6F
C++ 不用 typedef, struct 直接就可以用了
06/10 13:51, 6F

06/10 13:52, , 7F
修正:去include該檔都沒問題
06/10 13:52, 7F

06/10 13:52, , 8F
如果加了反而會變成兩個不同的東西有相同的名字
06/10 13:52, 8F

06/10 14:04, , 9F
你好~typedef我認知是 定義struct並且給一個(以上)別名之類的
06/10 14:04, 9F

06/10 14:05, , 10F
我是不清楚 看很多他人寫的程式都很愛使用typedef struct
06/10 14:05, 10F

06/10 14:05, , 11F
但是實際上的好處以及在我問的問題上 差異在哪裡!!
06/10 14:05, 11F

06/10 14:16, , 12F
定義 struct 不需要使用到 typedef, typdef 只是定義別名
06/10 14:16, 12F

06/10 14:23, , 13F
C語言不像C++可以直接這樣寫 struct s1{s1 *p2s1;};
06/10 14:23, 13F

06/10 14:24, , 14F
只能 typedef struct{int a;} s1; 來定義一個struct類型叫s1
06/10 14:24, 14F

06/10 14:26, , 15F
要做node就要這樣 typedef struct s1{ struct s1 *p; } S2;
06/10 14:26, 15F

06/10 14:40, , 16F
謝謝各位 ~我用了typedef的話我在.h那樣寫 為什麼會認不到
06/10 14:40, 16F

06/10 14:41, , 17F
在沒有extern"C"的情況下....
06/10 14:41, 17F

06/10 14:51, , 18F
因為它會找到兩個 FU
06/10 14:51, 18F

06/10 14:51, , 19F
一個是 typedef struct FF { blah } FU;
06/10 14:51, 19F

06/10 14:51, , 20F
一個是 struct FU;
06/10 14:51, 20F

06/10 14:52, , 21F
而這兩個 FU 定義是不同的, 一個是 struct FF 一個是 FU
06/10 14:52, 21F

06/10 14:55, , 22F
所以說struct FU是定義嚕?
06/10 14:55, 22F

06/10 14:56, , 23F
class FU的話是宣告 struct是定義?
06/10 14:56, 23F

06/10 14:59, , 24F
是宣告, 但你宣告了 FU 是 struct 結果定義它其實是別名
06/10 14:59, 24F

06/10 15:01, , 25F
看下篇 littleshan 寫的吧~ 比較清楚 lol
06/10 15:01, 25F
文章代碼(AID): #1ABqYms6 (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1ABqYms6 (C_and_CPP)