So I'm just getting to grips with C++ and progressing onto using header files. Thing is, I'm totally confused. I've read a documentation but none to make me understand it well enough.
I'm just making a silly 'game' which is interactive, it will probably be discarded and thought I could practice use on header files. This is my file structure:
terminal_test
├── core.cpp
└── game
├── game.cpp
└── game.h
Now, here is my core.cpp:
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include "game/game.h"
using namespace std;
void mainMenu();
void rootInterface() {
cout << "root#system:~# ";
}
int main() {
system("clear");
usleep(2000);
mainMenu();
return 0;
}
void mainMenu() {
int menuChoice = 0;
cout << "[1] - Start Game";
cout << "[2] - How To Play";
cout << endl;
rootInterface();
cin >> menuChoice;
if ( menuChoice == 1 ) {
startGame();
} else if ( menuChoice == 2 ) {
cout << "This worked.";
}
}
Everything else works fine but startGame(); under my menu choice. When I compile using g++ core.cpp game/game.cpp it bounces back with this error: undefined reference to startGame();. I firstly did some troubleshooting to see if it was properly finding game.h by changing the #include "game/game.h" to something like #include "game.h" without the directory listed inside and it gave me a game.h could not be found so I know it's recognising it, just not compiling at all.
Here is my game.h:
#ifndef GAME_H // Making sure not to include the header multiple times
#define GAME_H
#include "game.h"
void startGame();
#endif
game.cpp:
#include <iostream>
#include <stdio.h>
#include "game.h"
int main(int argc, char const *argv[]) {
void startGame() {
cout << "It worked.";
}
return 0;
}
My file structure isn't named properly either, I just threw it in because it was something to just get to grips with header files in C++.
So, here are my questions:
1) - What is this error specifically saying and what should I do to fix it?
2) - How do header files communicate and work with other files and is there clear documentation/guides out there that can help?
Local function definitions are not what you want here:
#include <iostream>
#include <stdio.h>
#include "game.h"
int main(int argc, char const *argv[]) {
// an attempt to define startGame() inside of main()
void startGame() {
cout << "It worked.";
}
return 0;
}
main is not needed in your game.cpp file. You should define startGame() outside of main, like this:
#include <iostream>
#include <stdio.h>
#include "game.h"
// definition of startGame
void startGame() {
cout << "It worked.";
}
Related
So I'm writing a POS system for a project at school and I'm having trouble declaring the call method for each file to access the said methods
main.cpp
#include <iostream>
#include <windows.h>
int main()
{
AppUI UI;
SecuritySys SecSysFunc;
EditBook BookFunc;
UI.MainMenu();
}
AppUI.cpp
#include <iostream>
#include <windows.h>
#include <iomanip>
#include <string>
#include <cstring>
#include <algorithm>
#include <unistd.h>
#include <stdio.h>
#include "SecuritySys.h"
#include "AppUI.h"
#include "EditBook.h"
AppUI UI;
SecuritySys SecSysFunc;
EditBook BookFunc;
using namespace std;
void AppUI::MainMenu()
{
//variable declarations
int opt;
MenuStart:
system("CLS");
TitleHeader();
setTxtColor(10);
PageTitle("Main Menu");
string Menu[] = {"Add Books", "Search Books", "View Books", "Delete Book", "Exit"};
cout << "1.\tAdd Books" << endl;
cout << "2.\tSearch Books" << endl;
cout << "3.\tView Books" << endl;
cout << "4.\tDelete Books" << endl << endl;
cout << "0.\tExit";
cout << "\n\nEnter Option: ";
cin >> opt;
switch(opt)
{
case 1:
BookFunc.AddBook();
break;
case 2:
BookFunc.AddBook();
break;
case 3:
BookFunc.AddBook();
break;
case 4:
BookFunc.AddBook();
break;
case 0:
SecSysFunc.Logout();
break;
default:
cout << "Invalid option!";
sleep(1);
goto MenuStart;
}
}
AppUI.h
#ifndef APPUI_H
#define APPUI_H
class AppUI
{
public:
void MainMenu();
void AddBook();
void SearchBook();
private:
};
#endif // APPUI_H
EditBook.cpp
#include <iostream>
#include <windows.h>
#include <iomanip>
#include <string>
#include <cstring>
#include <algorithm>
#include <unistd.h>
#include <stdio.h>
#include "SecuritySys.h"
#include "AppUI.h"
#include "EditBook.h"
AppUI UI;
SecuritySys SecSysFunc;
EditBook BookFunc;
using namespace std;
void EditBook::AddBook()
{
system("CLS");
UI.AddBook();
}
SearchByTitle(string searchTxt)
{
cout << "Enter search by title code here";
system("pause");
UI.MainMenu();
}
EditBook.h
#ifndef EDITBOOK_H
#define EDITBOOK_H
class EditBook
{
public:
void AddBook();
void SearchBook();
void ViewBooks();
void DeleteBooks();
protected:
private:
};
#endif // EDITBOOK_H
SecuritySys.cpp
#include <iostream>
#include <windows.h>
#include <iomanip>
#include <string>
#include <cstring>
#include <algorithm>
#include <unistd.h>
#include <stdio.h>
#include "SecuritySys.h"
#include "AppUI.h"
#include "EditBook.h"
AppUI UI;
SecuritySys SecSysFunc;
EditBook BookFunc;
using namespace std;
void SecuritySys::Login()
{
UI.MainMenu();
}
void SecuritySys::Logout()
{
exit(0);
}
SecuritySys.h
#ifndef SECURITYSYS_H
#define SECURITYSYS_H
class SecuritySys
{
public:
void Login();
void Logout();
private:
};
#endif
When I add AppUI UI; SecuritySys SecSysFunc; EditBook BookFunc; to the top of AppUI.cpp EditBook.cpp and SecuritySys.cpp I get an error saying multiple definition of UI,SecSysFunc and the BookFunc. But if I don't add them at the top, then the BookFunc.AddBook(); for example, the method can't be recognized and therefor can't be called or used. What am I doing wrong here?
You are getting a multiple definition error because you are just redeclaring the objects UI, SecSysFunc and BookFunc. You need to make it clear to the compiler that these identifiers point to the same object. You can do so by picking one of the four declarations to be the definition, leave those lines as is. But to the declarations in other code files add extern before the declaration. This will tell the compiler to look in other linked object files for the definition of those objects
Super confused as to what is throwing the error when I try to compile my code. I'm currently trying to test a function I wrote by printing out the values it should extract from a file.
gameboard.cpp
#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include "error.h"
using namespace std;
int boardDim(ifstream & inputFile, unsigned int x, unsigned int y) {
inputFile.open; //error is thrown here
if (!(inputFile.is_open())) {
throw fileNotOpen;
}
else {
stringstream output(inputFile.getline); //error is also thrown here
if (output >> x) {
if (output >> y) {
return success;
}
return secBoardVarErr;
}
return firstBoardVarErr;
}
cout << x << endl;
cout << y << endl;
}
gameboard.h
#ifndef GAMEBOARD_H
#define GAMEBOARD_H
#include <iostream>
using namespace std;
//takes in dimensions of board from file
int boardDim(ifstream &, unsigned int, unsigned int);
#endif !GAMEBOARD_H
main function
#include "stdafx.h"
#include "functions.h"
#include "gamepieces.h"
#include "gameboard.h"
#include "error.h"
int main(int argc, char * argv[])
{
ifstream x("test.txt");
int test = 0;
cout << boardDim(x, 0, 0) << endl;
return success;
}
I'm only testing the function I declared and defined in the gameboard header and source files, so the other included files will be used in the future but have already been tested and are not throwing errors when I compile and run it.
Thank you!
inputFile.open is a function, same with inputFile.getline, so what you have here is a syntactic error. The correct syntax is:
inputFile.open()
and
inputFile.getline()
I am lost and ran out of things to try that I know. I am trying to call a function in my main and I keep getting an undefined reference error (undefined reference to 'ParkingController::parkingMenuControl()').
How can I solve this issue? I have tried to rename that call to the class and even tried to rename the class and non of that has worked. Below is my code. Thank you in advance for help.
ParkingConrtol.h
#ifndef PARKINGCONTROL_H_INCLUDED
#define PARKINGCONTROL_H_INCLUDED
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
using namespace std;
class ParkingController
{
public:
void parkingMenuControl();
int parkingOption;
private:
};
#endif
parkingControlMain.cpp
#include "parkingControl.h"
using namespace std;
ParkingController parkingMenuMain;
int main(){
cout << "Welcome, Would you like to view our menu for parking?"<< endl;
cout << "Enter 1 to view menu or 0 to leave." << endl;
cin>>parkingMenuMain.parkingOption;
if (parkingMenuMain.parkingOption == 0)
{
exit(-1);
}
else if (parkingMenuMain.parkingOption == 1)
{
parkingMenuMain.parkingMenuControl();
}
}
and lastly here is my function parkingControl.cpp
#include "parkingControl.h"
/*
This module sets up the menu for the parking controller.
In here one can view the drawer with the money stored in
it and select a parking gate to enter from.
*/
using namespace std;
ParkingController parkingControlMenu;
void ParkingController::parkingMenuControl()
{
//Doing some function
}
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.
I am still fairly new to NetBeans, and am writing code for class in C++. I am currently on my third project, and I have run into an error I can't seem to resolve when trying to compile+run my project. I have quadruple-checked my code, going so far as to copy code from a previous project. I have tried quiting, rebooting the computer, and starting NetBeans up again. I ran CppCheck on my code and it found no errors.
The error message:
build/Debug/MinGW-Windows/main.o: In function `main':
C:/Users/Martin/Documents/NetBeansProjects/Lab3/main.cpp:52: undefined reference to `Dictionary::Dictionary()'
C:/Users/Martin/Documents/NetBeansProjects/Lab3/main.cpp:52: undefined reference to `Dictionary::~Dictionary()'
I tried copying code from a previous project, and even with the exact same code as a previous project which works, it's still having this problem. Basically, the build is failing to recognize the Dictionary class.
What things can I check that might cause this problem? Any obscure (or even obvious) settings I can check? Should I just start a new project and copy my code over?
Edit: Adding main():
#include <cstdlib>
#include <iostream>
#include "Dictionary.h"
using namespace std;
/*
* argv[1] dictionary file
* argv[2] boggle board file
* argv[3] output file
*/
int main(int argc, char** argv) {
if (argc > 3) {
Dictionary dict;
dict.loadDictFile(argv[1]);
} else {
cout << "Not enough arguments. Needed: ./lab3 [dictionary file] "
"[board file] [output file]" << endl;
}
return 0;
}
And Dictionary.h:
#ifndef DICTIONARY_H
#define DICTIONARY_H
#include <string>
#include <set>
using namespace std;
class Dictionary {
public:
Dictionary();
Dictionary(const Dictionary& orig);
virtual ~Dictionary();
virtual void loadDictFile(char * fileName);
virtual bool find(string word);
private:
set<string> dict;
set<string> fullDictionary; // Contains all words, not just those 4+ char long.
};
#endif /* DICTIONARY_H */
And Dictionary.cpp:
#include "Dictionary.h"
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
#include <set>
//using namespace std;
Dictionary::Dictionary() {
}
Dictionary::Dictionary(const Dictionary& orig) {
dict = orig.dict;
fullDictionary = orig.fullDictionary;
}
Dictionary::~Dictionary() {
}
void Dictionary::loadDictFile(char* fileName) {
ifstream infile;
infile.open(fileName);
if (infile) {
while(!infile.eof()) {
string line;
getline(infile, line);
fullDictionary.insert(line);
if (line.size() > 3) {
dict.insert(line);
}
}
} else {
cout << "Dictionary File not loaded: " << fileName << endl;
}
}
bool Dictionary::find(string word){
if (dict.find(word) != dict.end()) {
return true;
} else {
return false;
}
}
Found my problem. Netbeans didn't consider the Dictionary class to be part of my project, so it wasn't compiling Dictionary.cpp. I added it in the Project window by right-clicking the Source Files folder and using Add existing item... menu option. Now it compiles fine.
Does anyone know why the class wouldn't be added if I used Netbean's New File interface and added to the project specifically?