2013-10-11 21 views
0

我有3個文件: - main.cpp中 - other.cpp - other.hC++跨多個.cpp文件調用函數?

我想調用在other.h聲明的函數,從main.cpp中,用代碼爲寫在other.cpp

我的代碼:

main.cpp中:

//#Allmyincludes 
#include "other.h" 

int main(int argc, const char *argv[]) 
{ 
    const char *file = argv[1]; 
    read(file); 
    return 0; 
} 

other.cpp:

//#Allmyincludes 
#include "other.h" 

void read(const char *file) 
{ 
    //code 
} 

other.h:

void read(const char *file); 

我得到的錯誤是:

main.cpp:(.text+0x44): undefined reference to 'read(char const*)'

read(),我使用main::variableName從主(沒有錯誤)中訪問的變量,但是我只是不能讓函數調用工作。 如果我試圖做other::read(file);也不起作用,因爲::是爲功能而不是文件。它給了我錯誤:'other' has not been declared.

任何解釋爲什麼我的頭文件/調用不起作用非常感謝。

+0

顯示你的編譯命令。如果使用GCC(即'g ++'),則注意到編譯器對程序參數的順序非常重要。 –

+0

包括iostream – Jost

回答

1

未定義的引用錯誤有很多原因。在你的情況下,從你所描述的,最有可能的是,你沒有編譯other.cpp

你需要添加other.cpp到你的項目/ makefile /命令行。

如需更詳細的幫助,您可能需要說明如何構建程序。代碼沒有任何問題,這是您構建程序的方式,也是問題所在。

+0

謝謝。 我只有g ++ main.cpp -Wall -o main – user2871213

0

嘗試

gcc -Wall main.cpp other.cpp -o mymain