This question already has answers here:
How do I compile a .cpp file just to object file without calling linker
(2 answers)
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 1 year ago.
I am struggling to identify the issue with my code in my class inheritance. I've searched many places but can't quite seem to find the right answer. I've made some progress to fix many errors before this, but haven't wrapped it all up quite yet.
The main issue I am running into is undefined references to either methods or constructors in many instances throughout my files. I'm sure I'm probably just missing something stupidly simple somewhere, but being fairly new to C++, it's difficult for me to pinpoint exactly where the issue lies.
Below are the files to my code:
dog.h
#ifndef DOG_H
#define DOG_H
#include <string>
using namespace std;
class Dog{
public:
Dog();
~Dog(){};
string dogName = "";
string Breed = "";
int age = 0;
int weight = 0;
bool subjectToDiscount = false;
int riskWeight = 0;
float riskPremium = 0;
float basePremium = 0;
virtual float getPremium();
virtual Dog getDog(char b);
protected:
virtual float getBasePremium();
private:
};
#endif //DOG_H
dog.cpp
#include <iostream>
#include <string>
#include "dog.h"
#include "breeds.h"
using namespace std;
//---default constructor---//
Dog::Dog(){
};
//---methods---//
float Dog::getBasePremium(){
float val = 0;
//calculate base premium based on weight
return val;
};
float Dog::getPremium(){
float val = 0;
//calculate actual premium for the dog in question
if(this->riskWeight == 0){
val = this->basePremium;
}else if(this->weight > this-> riskWeight){
val = this->riskPremium;
}else val = this->basePremium;
//add discount if applicable
if(this->subjectToDiscount && this->age > 13) val *= 0.80;
//add 25% if over 50kg
if(this->weight > 50) val *= 1.25;
return val;
};
Dog Dog::getDog(char b){
bool recognized = false;
Dog *pup;
while(!recognized){
switch (b)
{
case 'p':
pup = new Pitbull();
recognized = true;
break;
case 'd':
pup = new Doberman();
recognized = true;
break;
case 'r':
pup = new Rottweiler();
recognized = true;
break;
default:
cout << "Breed code not recognized, please try again...\n";
break;
}
}
return *pup;
}
int main(){
return 0;
}
breeds.h
#ifndef BREEDS_H
#define BREEDS_H
#include "dog.h"
#include <string>
using namespace std;
class Pitbull : public Dog{
public:
Pitbull();
~Pitbull(){};
protected:
private:
};
class Doberman : public Dog{
public:
Doberman();
~Doberman(){};
protected:
private:
};
class Rottweiler : public Dog{
public:
Rottweiler();
~Rottweiler(){};
protected:
private:
};
#endif //BREEDS_H
breeds.cpp
#include <iostream>
#include <string>
#include "dog.h"
#include "breeds.h"
using namespace std;
//---constructors---//
Pitbull::Pitbull(){
this->Breed = "a Pitbull";
this->basePremium = 30.20f;
this->riskPremium = 35.15f;
this->riskWeight = 20;
this->subjectToDiscount = false;
}
Doberman::Doberman(){
this->Breed = "a Doberman";
this->basePremium = 28.16f;
this->riskPremium = 30.00f;
this->riskWeight = 35;
this->subjectToDiscount = true;
}
Rottweiler::Rottweiler(){
this->Breed = "a Rottweiler";
this->basePremium = 28.00f;
this->riskPremium = 29.75f;
this->riskWeight = 45;
this->subjectToDiscount = false;
}
int main(){
return 0;
}
main.cpp
#include <iostream>
#include <iomanip>
#include <string>
#include "dog.h"
#include "breeds.h"
using namespace std;
int getDogCount(){
int retVal = 0;
cout << "Please enter the number of dogs in your household: ";
cin >> retVal;
return retVal;
}
void run(){
cout << setiosflags(ios::fixed);
cout << setprecision(2);
int dogCount = 0;
float totalPremium = 0;
dogCount = getDogCount();
for(int i = 1; i <= dogCount; i++){
float premium = 0;
char breedCode = '.';
string dogName = "";
Dog pup;
cout << "Enter the name of dog #" << i << ": ";
cin.ignore();
getline(cin, dogName);
cout << "Enter the breed code for " << dogName << ": ";
cin >> breedCode;
cin.ignore();
pup = pup.getDog(breedCode);
pup.dogName = dogName;
cout << "Enter the current age for " << dogName << ": ";
cin >> pup.age;
cin.ignore();
cout << "Enter the current weight for " << dogName << ": ";
cin >> pup.weight;
premium = pup.getPremium();
cout << "\n";
}
}
int main(){
run();
return 0;
}
These are the errors I get after attempting to compile the 3 .cpp files:
dog.cpp
C:\Users\whitl\AppData\Local\Temp\ccFdz6zr.o: In function `Dog::getDog(char)':
C:\Sandbox\C++\Beginning\Wooffurs/dog.cpp:46: undefined reference to `Pitbull::Pitbull()'
C:\Sandbox\C++\Beginning\Wooffurs/dog.cpp:50: undefined reference to `Doberman::Doberman()'
C:\Sandbox\C++\Beginning\Wooffurs/dog.cpp:54: undefined reference to `Rottweiler::Rottweiler()'
collect2.exe: error: ld returned 1 exit status
breeds.cpp
C:\Users\whitl\AppData\Local\Temp\ccbAKpbb.o: In function `Pitbull::Pitbull()':
C:\Sandbox\C++\Beginning\Wooffurs/breeds.cpp:10: undefined reference to `Dog::Dog()'
C:\Users\whitl\AppData\Local\Temp\ccbAKpbb.o: In function `Doberman::Doberman()':
C:\Sandbox\C++\Beginning\Wooffurs/breeds.cpp:18: undefined reference to `Dog::Dog()'
C:\Users\whitl\AppData\Local\Temp\ccbAKpbb.o: In function `Rottweiler::Rottweiler()':
C:\Sandbox\C++\Beginning\Wooffurs/breeds.cpp:26: undefined reference to `Dog::Dog()'
C:\Users\whitl\AppData\Local\Temp\ccbAKpbb.o:breeds.cpp:(.rdata$_ZTV10Rottweiler[_ZTV10Rottweiler]+0x10): undefined reference to `Dog::getPremium()'
C:\Users\whitl\AppData\Local\Temp\ccbAKpbb.o:breeds.cpp:(.rdata$_ZTV10Rottweiler[_ZTV10Rottweiler]+0x18): undefined reference to `Dog::getDog(char)'
C:\Users\whitl\AppData\Local\Temp\ccbAKpbb.o:breeds.cpp:(.rdata$_ZTV10Rottweiler[_ZTV10Rottweiler]+0x20): undefined reference to `Dog::getBasePremium()'
C:\Users\whitl\AppData\Local\Temp\ccbAKpbb.o:breeds.cpp:(.rdata$_ZTV8Doberman[_ZTV8Doberman]+0x10): undefined reference to `Dog::getPremium()'
C:\Users\whitl\AppData\Local\Temp\ccbAKpbb.o:breeds.cpp:(.rdata$_ZTV8Doberman[_ZTV8Doberman]+0x18): undefined reference to `Dog::getDog(char)'
C:\Users\whitl\AppData\Local\Temp\ccbAKpbb.o:breeds.cpp:(.rdata$_ZTV8Doberman[_ZTV8Doberman]+0x20): undefined reference to `Dog::getBasePremium()'
C:\Users\whitl\AppData\Local\Temp\ccbAKpbb.o:breeds.cpp:(.rdata$_ZTV7Pitbull[_ZTV7Pitbull]+0x10): undefined reference to `Dog::getPremium()'
C:\Users\whitl\AppData\Local\Temp\ccbAKpbb.o:breeds.cpp:(.rdata$_ZTV7Pitbull[_ZTV7Pitbull]+0x18): undefined reference to `Dog::getDog(char)'
C:\Users\whitl\AppData\Local\Temp\ccbAKpbb.o:breeds.cpp:(.rdata$_ZTV7Pitbull[_ZTV7Pitbull]+0x20): undefined reference to `Dog::getBasePremium()'
C:\Users\whitl\AppData\Local\Temp\ccbAKpbb.o:breeds.cpp:(.rdata$.refptr._ZTV3Dog[.refptr._ZTV3Dog]+0x0): undefined reference to `vtable for Dog'
collect2.exe: error: ld returned 1 exit status
main.cpp
C:\Users\whitl\AppData\Local\Temp\ccgKyBTC.o: In function `run()':
C:\Sandbox\C++\Beginning\Wooffurs/main.cpp:30: undefined reference to `Dog::Dog()'
C:\Sandbox\C++\Beginning\Wooffurs/main.cpp:40: undefined reference to `Dog::getDog(char)'
C:\Sandbox\C++\Beginning\Wooffurs/main.cpp:50: undefined reference to `Dog::getPremium()'
C:\Users\whitl\AppData\Local\Temp\ccgKyBTC.o:main.cpp:(.rdata$.refptr._ZTV3Dog[.refptr._ZTV3Dog]+0x0): undefined reference to `vtable for Dog'
collect2.exe: error: ld returned 1 exit status
Thank you to anyone that helps, I really appreciate it. Please give my any pointers on my code as well, and how to possibly better pose questions on Stack Overflow.
It looks as though you are doing something like:
g++ dog.cpp -o dog
Without the -c flag (for compile only, don't link) the compiler will attempt to make an executable from that one file.
Generally speaking you need to do one of the following:
Compile each cpp file separately, and then link at the end
# compilation
g++ -c dog.cpp -o dog.o
g++ -c breeds.cpp -o breeds.o
g++ -c main.cpp -o main.o
# now link the 3 object files into the exe
g++ -o myApp main.o dog.o breeds.o
Compile them in one go
g++ -o myApp main.cpp dog.cpp breeds.cpp
Use a makefile
all : myApp
# dog.o depends on dog.cpp & breeds.h. When those change, run line below
dog.o: dog.cpp breeds.h
gcc -c -o dog.o dog.cpp
breeds.o: breeds.cpp dog.h
gcc -c -o breeds.o breeds.cpp
main.o: main.cpp breeds.h dog.h
gcc -c -o main.o dog.cpp
# final app depends on the object files, when they change, recompile.
myApp: main.o dog.o breeds.o
gcc -o myApp main.o dog.o breeds.o
clean:
rm -f *.o
Use some IDE to manage this for you (or use something like cmake)
Related
I unable to find a solution to my problem, I think it has something to do with overloading functions but I can't seem to figure out how to resolve it.
here is my function.cpp
#include "CountLetter.h"
int Countletter(string sentence, char letter) {
int size = sentence.length();
int toReturn = 0;
for (int i = 0; i<= size; ++i) {
if (sentence[i] == letter) {
toReturn++;
}
}
return toReturn;
}
Here is my function.h
#ifndef FN_H
#define FN_H
#include <iostream>
using namespace std;
int CountLetter(string sentence, char letter);
#endif
My main.cpp
#include "CountLetter.h"
int main() {
string sent = "";
char let = ' ';
int times = 0;
cout << "Enter a sentence.\n";
getline(cin, sent);
cout << "Enter a letter.\n";
cin >> let;
times = CountLetter(sent, let);
cout << "The letter " << let << " occurred " << times << " time(s).\n";
return 0;
}
and finally my makefile
lab16: lab16.o CountLetter.o
g++ -std=c++11 -o lab16 lab16.o CountLetter.o
lab16.o: lab16.cpp
g++ -std=c++11 -o lab16.o -c lab16.cpp
CountLetter.o: CountLetter.h CountLetter.cpp
g++ -std=c++11 -o CountLetter.o -c CountLetter.cpp
and my errors
lab16.o: In function `main':
lab16.cpp:(.text+0xb4): undefined reference to
`CountLetter(std::__cxx11::basic_string<char, std::char_traits<char>,
std::allocator<char> >, char)'
collect2: error: ld returned 1 exit status
Makefile:2: recipe for target 'lab16' failed
make: *** [lab16] Error 1
Thanks!
C and C++ are case sensitive:
Definition:
int Countletter(string sentence, char letter) {
Usage:
times = CountLetter(sent, let);
When facing with a linker error, suspect misspelling as one of the scenarios.
Did you get their subtle difference?
Countletter
CountLetter
Your CountLetter function is in the function.h so
change your #include "CountLetter.h" into #include "function.h"
I'm facing a problem for the past couple of days.
First of all, I had a project that I've done. But now I've to split it's classes.
Here's how I split the classes (a class as an example):
Header file:
#ifndef QUESTION_H
#define QUESTION_H
#include <string>
#include <iostream>
#include <fstream>
#include "Answer.h"
using namespace std;
// Name -- hold a first and last name
class Question {
protected:
string type; // Type of the question, e.g MC or TF
string text; // Text of the question
public:
// Default constructor
Question ();
// Getters and setters
string getType();
string getText();
void setType (string t);
void setText (string t);
// displayText -- Display the text of the question, unformatted at present
void displayText();
// Template pattern -- algorithm in parent which does its work calling child methods
virtual void displayAnswers();
virtual void display ();
// Virtual pure functions that must be implemented by each derived class
virtual int grade (Answer*); // grade a given answer
virtual Answer* readAnswer(istream &); // read a user's answer
};
#endif
Alright, now here is the implementation:
#include "Question.h"
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
Question::Question () { type = ""; text = ""; }
// Getters and setters
string Question::getType() { return type; }
string Question::getText() { return text; }
void Question::setType (string t) { type = t; }
void Question::setText (string t) { text = t; }
// displayText -- Display the text of the question, unformatted at present
void Question::displayText() {
cout << text;
}
// Template pattern -- algorithm in parent which does its work calling child methods
void Question::displayAnswers(){ }// Require derived classes to implement
void Question::display () {
Question::displayText();
Question::displayAnswers(); // Call derived class's displayAnswers
}
// Virtual pure functions that must be implemented by each derived class
int Question::grade (Answer*){ return 0; } // grade a given answer
Answer* Question::readAnswer(istream &){ return 0; } // read a user's answer
Ok, so I've done the other classes the same exact way.
Now what's left is the MakeFile, here it is:
project: Question MCQuestion TFQuestion Answer IntAnswer CharAnswer Main
g++ -std=c++11 Question MCQuestion TFQuestion Answer IntAnswer CharAnswer Main -o project
.cc.o:
g++ -std=c++11 -c <−o#
Now when I try running make it brings up this message:
g++ Question.cpp -o Question
/usr/lib/gcc/i586-suse-linux/4.7/../../../crt1.o: In function `_start':
/home/abuild/rpmbuild/BUILD/glibc-2.17/csu/../sysdeps/i386/start.S:113: undefined reference to `main'
collect2: error: ld returned 1 exit status
make: *** [Question] Error 1
Can somebody explains it? or what am I doing wrong?
Thanks.
Edited:
Main.cc :
#include <iostream>
#include <fstream>
#include <string>
#include "Question.h"
#include "MCQuestion.h"
#include "TFQuestion.h"
#include "Answer.h"
#include "IntAnswer.h"
#include "CharAnswer.h"
#include <vector>
using namespace std;
int main () {
vector<Question *> questions; // Holds pointers to all the questions
ifstream infile ("questions.txt"); // Open the input file
int totalCorrect = 0; // Initialize the count from number of correct answers
// Read each question and place it into the questions vector
string questionType;
while ( getline (infile, questionType) ) {
if (questionType == "MC") {
MCQuestion *mc = new MCQuestion();
mc->read(infile);
questions.push_back(mc);
}
else if ( questionType[0] == 'T' or questionType[0] == 'F' ) {
TFQuestion* tf = new TFQuestion();
tf->read(infile);
tf->setAnswer(questionType[0]);
questions.push_back(tf);
}
else {
cout << "Input file is corrupt. Expected to find MC, T or F; found \"" << questionType << "\" instead." << endl;
}
}
infile.close();
// Pose each question, read and grade answers, tally total
int questionNo = 0;
for (auto &question: questions) {
// Pose the question
questionNo++; cout << questionNo << ". ";
question->display();
// Get the user's answer
Answer* ans = question->readAnswer(cin);
// Grade it and increment total
int correct = question->grade(ans);
totalCorrect = totalCorrect + correct
// Inform the user as to whether or not they got the question correct
cout << "Your answer was " << (correct?"":"not ") << "correct\n" << endl;
}
// Print the overall score
cout << "Your overall score is " << totalCorrect << "/"
<< questions.size() << endl;
return 0;
}
You create Makefile with lot of mistakes:
Should be something like this:
project: Question.o
g++ -std=c++11 $^ -o $#
.cc.o:
g++ -std=c++11 -c $< -o $#
add other dependencies into project in similar way, not forget defining main function in some of your .cc files.
so I'm doing some homework for my CompSci 2 class and have hit a couple snags. I can compile NBAplayer.h fine, but compiling client.cpp produces:
client.cpp:(.text+0x10a): undefined reference to
`NBAplayer::setName(std::basic_string,
std::allocator >)'
And trying to compile NBAplayer.cpp produces the following:
/usr/lib/gcc/i686-redhat-linux/4.5.1/../../../crt1.o: In function
_start': (.text+0x18): undefined reference tomain' collect2: ld
returned 1 exit status
These are the three files I have:
client.cpp
#include <iostream>
#include <string>
#include "NBAplayer.h"
using namespace std;
int main() {
struct NFLPlayer{
string name;
string currentTeam;
string Position;
string School;
};
bool playerCheck;
int playerType;
string playerName;
string playerTeam;
string playerPosition;
string playerSchool;
playerCheck = false;
NBAplayer player1;
while(playerCheck == false)
{
cout << "What kind of player would you like to create? (Enter 1 for NBA, 2 for NFL): "
<< endl;
cin >> playerType;
if(playerType = 1) {
}
else if(playerType = 2) {
cout << "Please enter your NBA Player's name: "
<< endl;
cin >> playerName;
player1.setName(playerName);
}
else {
cout << "Please check your input and try again!"
<< endl;
}
}
};
NBAplayer.h
#include <string>
class NBAplayer {
private:
std::string name;
std::string team;
char position;
std::string school;
public:
void setName(std::string playerName);
void setTeam(std::string teamName);
void setPosition(char playerPosition);
void setSchool(std::string schoolName);
std::string getName();
std::string getTeam();
char getPosition();
std::string getSchool();
};
NBAplayer.cpp
#include "NBAplayer.h"
#include <string>
void NBAplayer::setName(std::string playerName) {
name = playerName;
}
std::string NBAplayer::getName() {
return name;
}
void NBAplayer::setTeam(std::string teamName) {
team = teamName;
}
std::string NBAplayer::getTeam() {
return team;
}
void NBAplayer::setPosition(char playerPosition) {
position = playerPosition;
}
char NBAplayer::getPosition() {
return position;
}
void NBAplayer::setSchool(std::string schoolName) {
school = schoolName;
}
std::string NBAplayer::getSchool() {
return school;
}
I've read through quite a few stackoverflow questions referencing this, but I have a feeling I'm doing something wrong since I'm unable to compile. If you need any more information, please let me know!
You shouldn't compile a header file, so don't compile NBAPlayer.h.
You aren't linking your files together. You can do this by compiling each file individually using -c (to compile, not link), then compile the resulting .o files together. Or you can just give g++ all of the source files at once, which will ask it to compile and link them together.
1 when you encounter the error undefined reference to, actually , it's not a complier error but a linker error(The complie process includes complie, link and load).As you seee, you will find collect2: ld returned 1 exit status,which come from linkers.
when you complie client.cpp, you get
undefined reference to NBAplayer::setName(std::basic_string, std::allocator >)
because you don't compile NBAplayer.cpp together.The linker can't find the implements of NBAplayer::setName.
2 when you compile NBAplayer.cpp , you get
undefined reference to main
that's because you just want compile NBAplayer.cpp to a executable object, but every cpp must have a main func, and you don't have one , so you get that problem .
3 you should do like this :g++ client.cpp NBAplayer.cpp -o main, compile both of them .
I am following tutorials from youtube. It seems I have encountered an error I can't resolve by myself. The goal is to create a class called BMI, which takes users weight name and height and prints them out..
I'm trying to compile it using g++, and I suspect I'm not doing it right. Usually I just do g++ filename.cpp, as I should in this case?
The tutorial is originally in that Microsoft ....thing, I don't know it's name. Sorry
Thank you, the code is attached below.
The error
/tmp/ccRcewk3.o: In function `main':
Main.cpp:(.text+0x7d): undefined reference to `BMI::BMI()'
Main.cpp:(.text+0x89): undefined reference to `BMI::getWeight() const'
Main.cpp:(.text+0x9a): undefined reference to `BMI::getHeight() const'
Main.cpp:(.text+0xaf): undefined reference to `BMI::getName() const'
Main.cpp:(.text+0x14f): undefined reference to `BMI::~BMI()'
Main.cpp:(.text+0x184): undefined reference to `BMI::~BMI()'
collect2: ld returned 1 exit status
Main.cpp
#include <iostream>
#include <string>
#include "BMI.h"
using namespace std;
/**************************************************/
int main()
{
string name;
int height;
double weight;
cout << "Enter your name: ";
cin >> name;
cout << "Enter your height (cm): ";
cin >> height;
cout << "Enter your weight (kg): ";
cin >> weight;
BMI Student_1;
cout << endl << "Patient name: " << Student_1.getName() << endl <<
"Height: " << Student_1.getHeight() << endl <<
"Weight: " << Student_1.getWeight() << endl;
return 0;
}
/**************************************************/
BMI.h
// Header ==> Function Declarations
#include <iostream>
#include <string>
using namespace std;
// tu ide klasa
#ifndef BMI_H
#define BMI_H
class BMI
{
public:
//Default Constructor
BMI();
//Overload Constructor
BMI(string, int, double);
//Destructor
~BMI();
// Accessor functions
string getName() const;
// // // returns name of patient
int getHeight() const;
// // // returns height of patient
double getWeight() const;
// // // returns weight of patient
private:
// member variables
string newName;
int newHeight;
double newWeight;
};
#endif
BMI.cpp:
//Function definitions
#include "BMI.h"
// to access function inside a class
BMI::BMI()
{
newHeight = 0;
newWeight = 0.0;
}
BMI::BMI(string name, int height, double weight)
{
newName = name;
newHeight = height;
newWeight = weight;
}
BMI::~BMI()
{
}
string BMI::getName() const
{
return newName;
}
int BMI::getHeight() const
{
return newHeight;
}
int BMI::getWeight() const
{
return newWeight;
}
edit:
OK, thanks everyone, I got part of the problem solved. However, you got me a little confused with editing, so I will do over.
It seems that the original code is not working, and I feel it should. Anyway, the edited code from the question doesn't work either.
So, I will try to do it again. But thank you, now I know how to compile. :)
edit2:
Everything is working now, thank you very much.
You need to compile the main.cpp into Main.o and BMI.cpp into BMI.o.
g++ -c Main.cpp
g++ -c BMI.cpp
Then you need to link both object files into one executable (and link to the Standard C++ lib)
g++ -o myprog Main.o BMI.o -lstdc++
Run the example with
./myprog
There seem to be more bugs, I have no time to fix, please continue yourself. :-)
[marc#quadfork ~/test]$./myprog
Enter your name: foo
Enter your height (cm): 23
Enter your weight (kg): 2
Patient name:
Height: 0
Weight: 0
your function return noting in your BMI.cpp
try with this.
string BMI::getName() const
{
return newName;
}
int BMI::getHeight() const
{
return newHeight;
}
double BMI::getWeight() const
{
return newWeight;
}
This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 5 years ago.
I'm finally pretty desperate. So, in my c++ class we were instructed to use classes. We'd have the header file declare the class and functions while a separate .cpp file implements the it. Things should be working, but they're not and no solutions on the web seem to be working for me. I'm using the G++ compiler on linux for this, and it doesn't seem to work on either IDE's or the normal command line.
The error I'm getting in my TBook.h is this:
/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
/tmp/ccxqI6An.o: In function `TBook::TBook()':
TBook.cpp:(.text+0x3b): undefined reference to `Telephone::Telephone()'
TBook.cpp:(.text+0x100): undefined reference to `Telephone::Telephone()'
TBook.cpp:(.text+0x132): undefined reference to `Telephone::allNum(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
TBook.cpp:(.text+0x182): undefined reference to `Telephone::~Telephone()'
TBook.cpp:(.text+0x191): undefined reference to `Telephone::~Telephone()'
TBook.cpp:(.text+0x2b3): undefined reference to `Telephone::~Telephone()'
TBook.cpp:(.text+0x2e6): undefined reference to `Telephone::~Telephone()'
TBook.cpp:(.text+0x2fa): undefined reference to `Telephone::~Telephone()'
/tmp/ccxqI6An.o:TBook.cpp:(.text+0x370): more undefined references to `Telephone::~Telephone()' follow
/tmp/ccxqI6An.o: In function `TBook::write()':
TBook.cpp:(.text+0x4e1): undefined reference to `Telephone::getNumber()'
TBook.cpp:(.text+0x506): undefined reference to `Telephone::getAreaCode()'
TBook.cpp:(.text+0x53a): undefined reference to `Telephone::getName()'
/tmp/ccxqI6An.o: In function `TBook::lookup(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)':
TBook.cpp:(.text+0x6d4): undefined reference to `Telephone::getName()'
TBook.cpp:(.text+0x79e): undefined reference to `Telephone::Telephone(int, std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
/tmp/ccxqI6An.o: In function `TBook::print()':
TBook.cpp:(.text+0x880): undefined reference to `Telephone::getName()'
TBook.cpp:(.text+0x8e0): undefined reference to `Telephone::getNumber()'
TBook.cpp:(.text+0x8ff): undefined reference to `Telephone::getAreaCode()'
collect2: ld returned 1 exit status
[Finished in 0.3s with exit code 1]
I'm kind of not liking that the file is not receiving any of the Telephone class's methods. Here's what the code looks like for TBook.h:
#ifndef TBOOK_H
#define TBOOK_H
#include "Telephone.h"
class TBook{
private:
Telephone rolodex[10];
int current;
int max;
public:
TBook();
~TBook();
void add(Telephone);
void write();
bool is_full();
void print();
void check();
Telephone lookup(string);
};
#endif
And this is what TBook.cpp looks like:
#include <iostream>
#include <fstream>
#include <string>
#include "TBook.h"
#include "Telephone.h"
using namespace std;
TBook::TBook(){
current = 0;
max = 9;
cout << "Hello" << endl;
string line;
ifstream myfile ("rolodex.txt");
if (myfile.is_open()){
while ( getline (myfile,line) ){
cout << line << endl;
Telephone t;
t.allNum(line);
add(t);
}
myfile.close();
}else if (!myfile.is_open()){
ofstream myfile;
myfile.open ("rolodex.txt");
myfile << "This is an empty file (Relatively).";
myfile.close();
}
}
TBook::~TBook(){
}
void TBook::add(Telephone tel){
if (!is_full()){
rolodex[current] = tel;
current++;
}
}
void TBook::write(){
ofstream myfile;
myfile.open ("rolodex.txt");
for (int i = 0; i < current; ++i)
{
myfile << rolodex[i].getName() << "," << rolodex[i].getAreaCode() << "," << rolodex[i].getNumber() << "\n";
}
myfile.close();
}
bool TBook::is_full(){
if (current <= max){
return false;
}
return true;
}
Telephone TBook::lookup(string lookName){
for (int i = 0; i < current; ++i){
if (rolodex[i].getName() == lookName){
return rolodex[i];
}
}
return Telephone(100, "", "1000000");
}
void TBook::print(){
//Print the vairables
for (int i = 0; i < current; ++i){
cout << "Name: " << rolodex[i].getName() << endl;
cout << "Number: (" << rolodex[i].getAreaCode() << ") " << rolodex[i].getNumber() << endl;
}
}
void TBook::check(){
cout << "the message" << endl;
}
Since the problem seems to be arising with the Telephone class, I figure I should also show that code too
Telephone.h
..
#ifndef TELEPHONE_H
#define TELEPHONE_H
#include <iostream>
#include <string>
using std::string;
class Telephone{
private:
string name;
string num;
int areaCode;
public:
Telephone(int, string, string);
Telephone();
~Telephone();
bool setAreaCode(int);
//Setters
void setName(string);
void setNumber(string);
bool allNum(string);
//Getters
string getName();
string getNumber();
int getAreaCode();
//Checks
bool checkX(int);
bool checkY(int);
};
#endif
Telephone.cpp
..
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include "Telephone.h"
using namespace std;
Telephone::Telephone(){
areaCode = 0
name = "";
num = "";
}
Telephone::Telephone(int aCode, string nam, string number){
areaCode = aCode;
name = name;
}
Telephone::~Telephone(){
//Nope Nada
}
bool Telephone::allNum(string all){
size_t found = all.find_first_of(",");
//
string first = all.substr(0, found);
string second = all.substr((found)+1, found+1);
string third = all.substr( all.find_last_of(",")+1, all.length());
int x, y;
//convert string to int values
if(third.length() == 7){
x = atoi(third.substr(0,3).c_str()),
y = atoi(third.substr(3,4).c_str());
}else{
cerr << "Your phone number is not valid" << endl;
}
int ac = atoi(second.substr(0, second.length()).c_str());
setName(first);
if (!setAreaCode(ac)){
setAreaCode(100);
return true;
}
if (!checkX(x) || !checkY(y)){
setNumber("1000000");
}else{
setNumber(third);
}
cerr << "The info provided is not valid" << endl;
return false;
}
void Telephone::setNumber(string number){
num = number;
}
bool Telephone::setAreaCode(int aCode){
if(aCode >= 100 && aCode <= 999){
areaCode = aCode;
return true;
}
return false;
}
void Telephone::setName(string theName){
name = theName;
}
bool Telephone::checkX(int x){
if(x >= 100 && x <= 999){
return true;
}
cerr << "First three digits are not valid" << endl;
return false;
}
bool Telephone::checkY(int y){
if(y >= 0000 && y <= 9999){
return true;
}
cerr << "Last four digits are not valid" << endl;
return false;
}
//Getters
string Telephone::getName(){
return name;
}
string Telephone::getNumber(){
return num;
}
int Telephone::getAreaCode(){
return areaCode;
}
And my main file (also called test.cpp) looks like this:
test.cpp
#include <iostream>
#include <string>
#include "TBook.h"
#include "Telephone.h"
using namespace std;
int main(int argc, char const *argv[])
{
//Create a Rolodex
TBook addressBook;
return 0;
}
I'm also getting this error with test.cpp
/tmp/ccl8anRb.o: In function `main':
test.cpp:(.text+0x24): undefined reference to `TBook::TBook()'
test.cpp:(.text+0x38): undefined reference to `TBook::~TBook()'
collect2: ld returned 1 exit status
I think this is mostly a compiling error, but I'm still not sure, and I feel like I'm the setup of the meme "My code doesn't work, and I don't know why." Usually I would bash the code and try different methods until it works, but I simply don't have the time. I therefore need your help.
This is a linker error. Try:
g++ test.cpp Telephone.cpp -o test
Basically, the linker is complaining about functions you used but didn't provide an implementation for. To see all the steps the compiler performs for you, throw in a -v:
g++ -v test.cpp Telephone.cpp -o test