2016-09-18 87 views
-4

對不起超新手問題。我不熟悉C++和任何類型的編程,但是我創建了這些程序來讀取用戶輸入,然後讀取它的命令和文件。我想包含文件a.h,但是我遇到了麻煩。它告訴我,我的函數main被重新定義了,但是當我把它拿出來時,它會吐出更多的錯誤。我正在考慮可能是否有其他陳述?任何建議讓我去?有沒有一種方法可以將我的文件包含在C++中?

文件名tryout.cpp

#include <iostream> 
#include <string.h> 
#include "a.h" 

using namespace std; 

int main() 
{ 
string cmd,command,file1,file2; 
cout << "prompt<<"; 
cin >> cmd; 
int len = cmd.length(); 

int temp = cmd.find('<'); 
command = cmd. substr(0,temp); 
cout << "COMMAND: " << command << "\n"; 

cout << "File Redirection: " << cmd.at(temp) << "\n"; 

int temp1 = cmd.find('>'); 
file1 = cmd.substr(temp+1,temp1-temp-1); 
cout << "FILE: " << file1 << "\n"; 

cout << "File Redirection: " << cmd.at(temp1) <<"\n"; 

file2 = cmd.substr(temp1+1, len-1); 
cout << "File: " << file2 <<"\n"; 

return 0; 
} 

文件名 「A.H」

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

using namespace std; 

int main() 
{ 

string cmd,command1,command2,command3; 
cout << "prompt<<"; 
cin >> cmd; 
int len = cmd.length(); 

int temp = cmd.find('|'); 
command1 = cmd.substr(0,temp); 
cout << "COMMAND: " << command1 << "\n"; 

cout << "PIPE: " << cmd.at(temp) << "\n"; 

command2 = cmd.substr(temp+1,len-1); 
cout << "COMMAND: " << command2 << "\n"; 

cout << "PIPE: " << cmd.at(temp) << "\n"; 

command3 = cmd.substr(temp+2,len-2); 
cout << "COMMAND: " << command3 << "\n"; 



return 0; 
} 
+2

這種錯誤信息以哪種方式不清楚。你的頭文件中實際上有'main()'的定義。你想實現什麼? –

+1

我毫不猶豫地建議這有[XY問題]的非常強烈的氣味(http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。 – WhozCraig

+0

你爲什麼想要這樣做? – Galik

回答

0

你不能有多個主()函數。編譯時,C++編譯器將獲取頭文件的內容,並將它們添加到#include語句所在的位置。如果它找到多個main()函數,它不知道在哪裏設置可執行文件的起始點。你將不得不重新命名頭文件功能。還要注意,通常的做法是不將函數定義包含在頭文件中,而不是使用函數聲明並在其他.cpp或預編譯的.lib文件中定義。

我發現this文章有助於瞭解標題如何工作。

+0

這也許值得注意的是,這也適用於其他函數定義。 –

+0

正確,謝謝你的補充。不過,我確實認爲這通常發生在main()被意外地聲明兩次時。 –

0

你不能有兩個主要功能。如果你想包含你的文件,你應該把所有東西放在一個函數中,或者更好地構建一個類。

1

「.h」後綴用於「頭文件」文件。如果你想要一個表單信,從你的單元公司說,頂部是一堆東西,告訴你公司名稱,聯繫方式等。

C++中的「頭文件」是一個主要提供定義,您可能需要在多個「.cpp」文件之間共享。一個「.cpp」文件通常是一個「編譯單元」,一個編譯器希望變成一個類似命名的「目標文件」的獨立文件。

所以,在你告訴我們你的利益分歧是錯誤的。 「.h」文件中實際上已經執行 main。

當編譯器將讀取你的「的.cpp」的文件,它讀取的iostreamstring.h頭,並然後a.h讀取,這包括實施main。然後,它返回到處理tryout.cpp,在那裏它看到另一個main的實現。

解決方案:從a.h刪除主。

相關問題