看板 C_and_CPP 關於我們 聯絡資訊
不好意思 我現在自己想問題測試 其實我對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
Ebergies:應該是 typedef 不能吧... 06/10 13:48
zlw:如果你不喜歡在main.cpp放extern "C"那可以學stdio.h的作法 06/10 13:50
QQ29:我拿掉typedef 可以過了?但是 原因差別在哪呢@@ 06/10 13:50
zlw:#ifdef __cplusplus (詳細的你google吧,推文不好講) 06/10 13:50
zlw:這樣做就可以像stdio.h一樣,不管是C或C++去include該檔都沒ok 06/10 13:51
Ebergies:C++ 不用 typedef, struct 直接就可以用了 06/10 13:51
zlw:修正:去include該檔都沒問題 06/10 13:52
Ebergies:如果加了反而會變成兩個不同的東西有相同的名字 06/10 13:52
QQ29:你好~typedef我認知是 定義struct並且給一個(以上)別名之類的 06/10 14:04
QQ29:我是不清楚 看很多他人寫的程式都很愛使用typedef struct 06/10 14:05
QQ29:但是實際上的好處以及在我問的問題上 差異在哪裡!! 06/10 14:05
Ebergies:定義 struct 不需要使用到 typedef, typdef 只是定義別名 06/10 14:16
zlw:C語言不像C++可以直接這樣寫 struct s1{s1 *p2s1;}; 06/10 14:23
zlw:只能 typedef struct{int a;} s1; 來定義一個struct類型叫s1 06/10 14:24
zlw:要做node就要這樣 typedef struct s1{ struct s1 *p; } S2; 06/10 14:26
QQ29:謝謝各位 ~我用了typedef的話我在.h那樣寫 為什麼會認不到 06/10 14:40
QQ29:在沒有extern"C"的情況下.... 06/10 14:41
Ebergies:因為它會找到兩個 FU 06/10 14:51
Ebergies:一個是 typedef struct FF { blah } FU; 06/10 14:51
Ebergies:一個是 struct FU; 06/10 14:51
Ebergies:而這兩個 FU 定義是不同的, 一個是 struct FF 一個是 FU 06/10 14:52
QQ29:所以說struct FU是定義嚕? 06/10 14:55
QQ29:class FU的話是宣告 struct是定義? 06/10 14:56
Ebergies:是宣告, 但你宣告了 FU 是 struct 結果定義它其實是別名 06/10 14:59
Ebergies:看下篇 littleshan 寫的吧~ 比較清楚 lol 06/10 15:01