2014-08-30 154 views
0

當我在eclipse中編譯C++項目時,它向我顯示錯誤,指出IO.cpp中的所有函數都已定義。在Eclipse中構建項目時出錯

這是我的代碼:

文件:IO.cpp

#include <string> 
#include <iostream> 

using namespace std; 

void print(string line) { 
    cout << line; 
} 

void println(string line) { 
    cout << line << endl; 
} 

void printError(string message, string error, string file) { 
    cout << "An error occurred!" << endl; 
    cout << "Message: "+ message << endl; 
    cout << "Error: "+ error << endl; 
    if(file != "") { 
     cout << "File/Method: "+ file << endl; 
    } 
} 

文件:main.cpp中

#include <string> 
#include <iostream> 
#include "IO.cpp" 

using namespace std; 

int main() 
{ 
    println("Hello world!"); 
} 
+3

規則1:不要在其他文件中包含'.cpp'文件。 – CoryKramer 2014-08-30 17:29:15

回答

0

您應該main.cpp

#include "IO.cpp" 
刪除下面的行

An D收藏以下行AFER using namespace std

void print(string line); 
void println(string line); 
void printError(string message, string error, string file); 

如果包括再次cpp文件,該文件也存在於你的項目源列表(編譯文件),你的程序將獲得多重定義爲這是不允許的相同功能在C++中。另一方面,這裏提出的替代方案由函數的聲明組成,聲明允許呈現多次,但在第一次使用之前必須呈現至少一次。

標準的做法是將一個頭文件中的聲明(爲前:IO.h),幷包括兩個IO.cppmain.cpp

進一步閱讀這個頭文件:
Difference between declarations and definitions

+0

謝謝我認爲編譯器不會編譯IO.cpp,如果它不包含在main.cpp中(如PHP) – Manulaiko 2014-08-30 17:44:41

0

您在包括模塊IO.cpp模塊main.cpp

#include "IO.cpp" 

所以你已經得到了函數定義在兩個模塊中:IO.cppmain cpp

您應該創建一個頭文件,例如IO.h並放置所有函數聲明。然後,你必須包括在IO.cpp這個頭文件和main.cpp

例如

IO.h

#include <string> 


void print(std::string line); 

void println(std::string line); 

void printError(std::string message, std::string error, std::string file); 

IO.cpp

#include <string> 
#include <iostream> 
#include <IO.h> 

using namespace std; 

void print(string line) { 
    cout << line; 
} 

void println(string line) { 
    cout << line << endl; 
} 

void printError(string message, string error, string file) { 
    cout << "An error occurred!" << endl; 
    cout << "Message: "+ message << endl; 
    cout << "Error: "+ error << endl; 
    if(file != "") { 
     cout << "File/Method: "+ file << endl; 
    } 
} 

的main.cpp

#include <IO.h> 

//... 
+0

謝謝我認爲編譯器不會編譯IO.cpp,如果它不包含在main .cpp(如PHP) – Manulaiko 2014-08-30 17:45:09