我想弄清楚如何制作一个由单独文件组成的程序。我读了这篇文章:
Function Implementation in Separate File
但是一直没有成功。我有 3 个文件:main.cpp、func.cpp、time.h,当我编译时,我收到此错误消息:
duplicate symbol getOpen(std::basic_ofstream<char, std::char_traits<char> >&)in:
/var/folders/kp/57zkm0tn1q7b7w0cs7tlf98c0000gn/T//cczaW1Px.o
/var/folders/kp/57zkm0tn1q7b7w0cs7tlf98c0000gn/T//ccvOCRgc.o
ld: 1 duplicate symbol for architecture x86_64
collect2: ld returned 1 exit status
我不知道这是什么意思。我基本上只是想打开一个文件,写入它,然后关闭它。我也刚刚创建了一个对象并对其进行了测试。我知道问题出在 func.cpp 上,因为当我删除它时它起作用了。有人可以建议吗?谢谢。
我输入这个来编译:g++ main.cpp func.cpp
。
这是我的代码:
时间.h
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <fstream>
using namespace std;
class Time
{
private:
int seconds;
int minutes;
int hours;
public:
Time(int=0, int=0, int=0);
Time(long);
void showTime();
};
Time::Time(int sec, int min, int hour)
{
seconds = sec;
minutes = min;
hours = hour;
}
Time::Time(long sec)
{
hours = int(sec / 3600);
minutes = int((sec % 3600)/60);
seconds = int( (sec%60) );
}
void Time::showTime()
{
cout << setfill('0')
<< setw(2) << hours << ':'
<< setw(2) << minutes << ':'
<< setw(2) << seconds << endl;
}
func.cpp
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int getOpen(ofstream& fileOut)
{
string filename = "outfile.txt";
fileOut.open(filename.c_str());
if( fileOut.fail())
{
cout << "\nFailed to open file.\n";
exit(1);
}
else
return 0;
}
main.cpp
#include <iostream>
#include "time.h"
#include "func.cpp"
int main()
{
ofstream outFile;
Time t1;
t1.showTime();
getOpen(outFile);
outFile << "This is a test" << endl;
outFile.close();
return 0;
}
最佳答案
您将 "func.cpp"
包含到 main.cpp
中,因此您有一个 getOpen
的双重声明。
关于c++ - 在 C++ 中为函数和类使用多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20228420/