查看完整版本: (已解決)關於將副程式寫在另外一個.cpp檔的問題
頁: [1]

在那裡 發表於 2016-8-26 10:06 PM

(已解決)關於將副程式寫在另外一個.cpp檔的問題

本帖最後由 在那裡 於 2016-8-27 04:48 PM 編輯

假設我有一個專案,除了main.cpp以外,我又建立了一個001.cpp與002.cpp檔案加入專案
可是當我在002.cpp檔呼叫了001.cpp檔的副程式後,編譯器卻顯示說找不到此函式……這個問題該如何解決?
<div></div>

kilean 發表於 2016-8-26 11:21 PM

基本上,我會將function 宣告在.h檔,在.cpp檔實作,無論誰要使用,就include該function的.h檔,舉個例子:
//----001.h----
int func1();

//----001.cpp----
int func1()
{
    //code here
    return 0;
}

//----002.h----
int func2();

//----002.cpp----
#include "001.h"
int func2()
{
    return func1();
}

//----main.cpp----
#include "002.h"
int main()
{
    func2();
    return 0;
}

allenbody 發表於 2016-8-26 11:30 PM

本帖最後由 allenbody 於 2016-8-28 01:15 AM 編輯

你沒寫header阿
加個 001.h file 裡面放 001提供給002的 function prototype.// file: 001.h
void 001_fun();

//--------------------------
// file: 002.cpp
#include "001.h"

void fun2(void)
{
     // reference from 001.cpp
     001_fun();
}



需要給外部使用的function 就需要讓他知道function 有宣告在哪




在那裡 發表於 2016-8-27 04:47 PM

哦哦哦哦哦
懂了!
也有高人告訴我說其實只要在上面寫出函數原型及可,問題已經解決了!
感謝各位大大!

crowofblack 發表於 2016-8-28 04:45 PM

不一定需要header file
也可以在你想呼叫的地方先宣告函數原型
但前面必須加上extern關鍵字, 讓編譯器知道這函數是外部函數
這樣編譯器就會自動幫你找這個函數在哪個檔案裡<br><br><br><br><br><div></div>
頁: [1]