Using Multiple Files in C++ for functions and classes - c++

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;
}

You included "func.cpp" into main.cpp, so you have a double declaration of getOpen.

You shouldn't #include "func.cpp" into main.cpp.
Well, it depends on how you compile your program. If you compile only main.cpp, then you should include func.cpp. But that's not a nice way to write a program, and I hope you are not going to do that.
What you might want to do is to compile main.cpp and func.cpp separately (using gcc -c) and then link the .o files. That would be perfectly ok if you don't include one .cpp file into another. But when you include func.cpp into main.cpp, both of the .o files define getOpen function. That causes the error.
So: just remove the #include in main.

Related

‘gettimeofday’ cannot be used as a function

What am I missing here, this is my main program, I also have a makefile and everything works the error is somewhere in here.
#include <iostream>
#include <observer.h>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]) {
std::fstream in;
int gettimeofday;
//CPUtypeandmodel
struct timeval now;
gettimeofday(&now, NULL);
cout << "Status report as of : " << ctime((time_t*)&now.tv_sec) << endl;
// Print machine name
in.open("/proc/sys/kernel/hostname");
string s;
in >> s;
cout << "Machine name: " << s << endl;
in.close();
return 1;
} //end main
When I try and make the file this happens
observer.cpp: In function ‘int main(int, char**)’:
observer.cpp:13:26: error: ‘gettimeofday’ cannot be used as a function
gettimeofday(&now, NULL);
^
<builtin>: recipe for target 'observer.o' failed
make: *** [observer.o] Error 1
You named a local int variable gettimeofday, which prevents you from calling the function gettimeofday() three lines later. Don't do that. Name the variable something else, or (given it seems unused) just get rid of it.
Your int gettimeofday; is shadowing the function with the same name. You don't even need that variable so remove it.
You need to include ctime and sys/time.h for the functions and classes you use.
You open the file /proc/sys/kernel/hostname for writing, which will fail unless you run the program as root.
The casting to time_t* is not necessary since &now.tv_sec is already a time_t*.
#include <sys/time.h>
#include <ctime>
#include <fstream>
#include <iostream>
#include <string>
int main() {
// CPUtypeandmodel
timeval now;
if(gettimeofday(&now, nullptr) == 0) // check for success
std::cout << "Status report as of : " << std::ctime(&now.tv_sec) << '\n';
// Print machine name
if(std::ifstream in("/proc/sys/kernel/hostname"); in) { // open for reading
std::string s;
if(in >> s) // check for success
std::cout << "Machine name: " << s << '\n';
} // no need to call in.close(), it'll close automatically here
return 1; // This usually signals failure. Return 0 instead.
} // end main

Can't read file in Xcode - Using C++

Am using OSx(Capitan)'s Xcode to code my C++ projects. I am trying Xcode to code C++ for the first time (Not that familiar with C++ also).I have a C++ project named registration, all my Cpp and Header files are inside this directory. I need to read from a file named rinput.txt and output it to a new file named routput.txt. I have tried Visual Studio and it worked perfectly fine for me. Is there anything special I need to do in Xcode? I have already put my rinput.txt in my main directory(where all my cpp and header files resides). What should I need to do to make it work? Guys any idea?
main.cpp
#include <iostream>
#include <fstream>
#include "course.h"
#include "regist.h"
using namespace std;
int main()
{
ifstream infile( "rinput.txt" );
if( !infile ) return -1;
Registration R;
infile >> R;
ofstream ofile( "routput.txt" );
ofile << R
<< "Number of courses = " << R.GetCount() << '\n'
<< "Total credits = " << R.GetCredits() << '\n';
// Declare and initialize a Course, and modify
// its credits.
Course aCourse( "MTH_3020", 'B', 2 );
aCourse.SetCredits( 5 );
cout << aCourse << endl;
return 0;
}

Error: variable or field 'functionName' declared void

I have the following in a C++ header file, as shown below.
cmdtree.h:
#ifndef CMDTREE_H
#define CMDTREE_H
#include <iostream>
#include <fstream>
#include <string>
#include "functions.h" // different header where some functions are
#include "classes.h" // different header where classes are
using namespace std;
void printLine(string filename, int line);
void cmd_ask_name();
void cmd_look_suspect();
#endif /* CMDTREE_H */
Then, in a .cpp source file, I have the following typed exactly as below (with some filler from other extraneous functions cut out for brevity). There are no includes, nothing else but what's shown here. I'm wondering, also, if that was the right decision, but I've tried it several different ways so I just thought I'd give you the cleanest version of the error:
cmdtree.cpp:
void printLine(string filename, int line)
{
char descrip[11][500] = {0};
char *ch_arr = descrip[0];
fstream text;
int y = 0;
cout << "\nfile: " << filename << " line: " << line << endl;
text.open(filename,ios::in);
if (!text.is_open()) {
cout << "\nCould not open " << filename << "." << endl;
} else {
while (!text.eof())
{
ch_arr = descrip[y];
text.getline(ch_arr,500);
y++;
}
}
text.close();
ch_arr = descrip[line];
cout << " " << ch_arr << endl;
}
void cmd_ask_name()
{
}
void cmd_look_suspect() // look suspect
{
}
Upon compilation, I receive the following errors. The cause isn't obvious to me -- I've included in the header file. I even get the error when I include string at the top of the cpp file itself.
mkdir -p build/Debug/Cygwin_4.x-Windows
rm -f "build/Debug/Cygwin_4.x-Windows/cmdtree.o.d"
g++ -c -g -std=c++11 -MMD -MP -MF "build/Debug/Cygwin_4.x-Windows/cmdtree.o.d" -o build/Debug/Cygwin_4.x-Windows/cmdtree.o cmdtree.cpp
cmdtree.cpp:3:16: error: variable or field 'printLine' declared void
void printLine(string filename, int line)
^
cmdtree.cpp:3:16: error: 'string' was not declared in this scope
cmdtree.cpp:3:33: error: expected primary-expression before 'int'
void printLine(string filename, int line)
^
nbproject/Makefile-Debug.mk:70: recipe for target 'build/Debug/Cygwin_4.x-Windows/cmdtree.o' failed
make[2]: *** [build/Debug/Cygwin_4.x-Windows/cmdtree.o] Error 1
It appears that you're missing the following from your cmdtree.cpp:
#include "cmdtree.h"
It doesn't get included automatically just because it has the same root file name as the .cpp file.
Also, it's not a good idea to put "using namespace std;" in a header file. Rather explicitly use std::string in the header and then you can put "using namespace std;" in the .cpp file.

Conflicting Errors in Visual Studio (C++)

I have a function "PrintHeader" for my project, defined in io.cpp. Even though io.h is included in my main file, I get the error
error C3861: 'PrintHeader': identifier not found.
When I copy the function for PrintHeader into my main file, I get the errors
error LNK2005: 'void _cdeci PrintHeader(void)" (?PrintHeader##YAXXZ) already defined in io.obj.
and
error LNK1169: one or more multiply defined symbols found.
I can understand the second error set, since I do have it defined twice, but I don't understand why it doesn't work when I just remove the duplicate definition. Any help is greatly appreciated.
Main file
#include "stdio.h"
#include <iostream>
#include "io.h"
void PrintHeader()
{
cout << endl;
cout << "Month\tPrincipal\t Interest\t Balance" << endl;
cout << "-----\t---------\t---------\t---------" << endl;
}
int main()
{
cout << "Hello World\n";
PrintHeader();
getchar();
return 0;
}
io.cpp
#include <iostream>
#include <iomanip>
#include "io.h"
void PrintHeader (void)
{
cout << endl;
cout << "Month\tPrincipal\t Interest\t Balance" << endl;
cout << "-----\t---------\t---------\t---------" << endl;
}
io.h
#ifndef __IO_H__
#define __IO_H__
#include <string>
using namespace std;
void PrintHeader (void);
#endif
You are most likely including the wrong file in main.cpp. You can make sure it is the right file by right clicking on the include "io.h" and choosing open file.

Returning a vector of strings

I'm a bit confused with all the namespaces for vector and how to properly return a vector of strings in my class. Here is the code:
main.cpp
#include <fstream>
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <string>
#include "lab1.h"
using namespace std;
readwords wordsinfile;
words wordslist;
int main ( int argc, char *argv[] )
{
if ( argc != 2 ) {
// Looks like we have no arguments and need do something about it
// Lets tell the user
cout << "Usage: " << argv[0] <<" <filename>\n";
exit(1);
} else {
// Yeah we have arguements so lets make sure the file exists and it is readable
ifstream ourfile(argv[1]);
if (!ourfile.is_open()) {
// Then we have a problem opening the file
// Lets tell the user and exit
cout << "Error: " << argv[0] << " could not open the file. Exiting\n";
exit (1);
}
// Do we have a ASCII file?
if (isasciifile(ourfile)) {
cout << "Error: " << argv[0] << " only can handle ASCII or non empty files. Exiting\n";
exit(1);
}
// Let ensure we are at the start of the file
ourfile.seekg (0, ios::beg);
// Now lets close it up
ourfile.close();
}
// Ok looks like we have past our tests
// Time to go to work on the file
ifstream ourfile2(argv[1]);
wordsinfile.getwords(ourfile2);
lab1.h
#ifndef LAB1_H
#define LAB1_H
bool isasciifile(std::istream& file);
class readwords {
public:
int countwords(std::istream& file);
std::vector<std::string> getwords(std::istream& file);
};
class words {
public:
void countall( void );
void print( void );
};
#endif
lab1.cpp
#include <fstream>
#include <iostream>
#include <map>
#include "lab1.h"
#include <vector>
using std::vector;
#include <string>
using namespace std;
vector<string> readwords::getwords(std::istream& file) {
char c;
string aword;
vector<string> sv;
int i = 0;
while(file.good()) {
c = file.get();
if (isalnum(c)) {
if(isupper(c)) {
c = (tolower(c));
}
if(isspace(c)) { continue; }
aword.insert(aword.end(),c);
} else {
if (aword != "") {sv.push_back(aword);}
aword = "";
i++;
continue;
}
}
return sv;
}
Here is the error from compiling.
g++ -g -o lab1 -Wall -pedantic main.cpp lab1.cpp
In file included from lab1.cpp:4:0:
lab1.h:9:4: error: ‘vector’ in namespace ‘std’ does not name a type
lab1.cpp:48:54: error: no ‘std::vector<std::basic_string<char> > readwords::getwords(std::istream&)’ member function declared in class ‘readwords’
make: *** [lab1] Error 1
Why do I get this error and how do I fix it. Thank you for any help you can provide.
Ryan
You have to #include <vector> in the header file as well. Actually, including it in the header is enough, as all files including that header will implicitly also include <vector>.
The thing is your include order is:
#include "lab1.h"
#include <vector>
and since you use std::vector in the header (before including it) you get the error. Reversing the include order would fix the compilation error, but doesn't solve the underlying error - that lab1 uses symbols that weren't defined yet. The proper fix is to include <vector>.
The compiler looks at code in the order it's written. That also applies to #include directives: the contents of the file are treated as if they had been written in the file that #include's them. As #LuchianGrigore has mentioned, the best solution is to add
#include <vector>
to "lab1.h". But you could hide the problem by moving the #include <vector> in "lab1.cpp" so that it comes before the #include "lab1.h". That would make the error go away, because the compiler would have already read` before it started to read "lab1.h". That's not what you should do, but it's the kind of thing that can happen accidentally and hide the actual problem.