I am trying to figure out how to make a program consisting of separate files. I read this post:
Function Implementation in Separate File
But have not succeeded. I have 3 files: main.cpp, func.cpp, time.h and when I compile, I get this error message:
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
I have no idea what this means. I'm basically just trying to open a file, write to it, and close it. I also just created an object and tested it. I know the problem is from func.cpp because when I remove that it works. Can someone please advise? Thank you.
I type this to compile: g++ main.cpp func.cpp.
This is my code:
time.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;
}