[問題] compiler head file與多個檔在linuxm卮cc

看板C_and_CPP作者 (imio)時間11年前 (2012/10/06 18:02), 編輯推噓1(109)
留言10則, 6人參與, 最新討論串1/3 (看更多)
:開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Linux 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 請問一下, 我想用G++ 在linux 下compiler head file 和 cpp file (如g++ -g main.cpp -o main) 當我compiler hellowWorld.h 沒有問題. 如果我在compiler hellowWorld.cpp 錯誤為In function `_start':(.text+0x20): undefined reference to `main' collect2: ld returned 1 exit status. 如果compiler main.cpp 錯誤為 undefined reference to `HelloWorld::printGreeting()'collect2: ld returned 1 exit status 請問我要如何compiler才能把他們連起來? 餵入的資料(Input): 預期的正確結果(Expected Output): 錯誤結果(Wrong Output): 程式碼(Code):(請善用置底文網頁, 記得排版) 1 helloWorld.h: 2 #ifndef HELLOWORLD 3 #define HELLOWORLD 4 5 void helloWorld(); 6 7 #endif 8 9 10 helloWorld.cpp 11 #include "helloWorld.h" 12 #include <iostream> 13 14 void helloWorld() 15 { 16 std::cout << "Hello World!" << std::endl; 17 } 18 19 20 main.cpp: 21 #include "helloWorld.h" 22 23 int main() 24 { 25 helloWorld(); 26 return 0; 27 } 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 71.190.195.62

10/06 18:05, , 1F
1. compiler ← 名詞 compile ← 動詞
10/06 18:05, 1F

10/06 18:05, , 2F
2. header file 不需要拿去 compile
10/06 18:05, 2F

10/06 18:06, , 3F
3. gcc 要加上 -c 才會是「只編譯,不連結」
10/06 18:06, 3F

10/06 18:07, , 4F
4. 編譯出 main.o 與 HelloWorld.o 後再連結
10/06 18:07, 4F

10/06 18:08, , 5F
5. 不要一整行問題直接複製貼上,在BBS很難閱讀
10/06 18:08, 5F

10/06 18:11, , 6F
真的只有一行...
10/06 18:11, 6F

10/06 18:24, , 7F
helloworld.h 是不是應該用extern
10/06 18:24, 7F

10/06 18:40, , 8F
其實這可以直接編吧 g++ main.cpp helloword.h
10/06 18:40, 8F

10/06 18:59, , 9F
函式宣告不需要 extern; 樓上應該是想寫 helloWorld.cpp
10/06 18:59, 9F

10/06 23:09, , 10F
compiler 不負責把它們連起來
10/06 23:09, 10F
文章代碼(AID): #1GS07E_M (C_and_CPP)
文章代碼(AID): #1GS07E_M (C_and_CPP)