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;
}
Related
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)
I am trying to practice object oriented programming structure in c++. I have written some piece of code. But I got an undefined reference error.
I've tried to build with clion ide but it gave me error. I've tried to compile it on linux terminal using g++ command but it gave me same error.
Account.h
#ifndef ACCOUNT_H
#define ACCOUNT_H
class Account
{
public:
Account ();
Account(double init_balance);
double getBalance();
void deposit(double amt);
void withdraw(double amt);
private:
double balance;
};
#endif // ACCOUNT_H
Account.cpp
#include "Account.h"
#include <iostream>
using namespace std;
Account::Account(double init_balance)
:balance(init_balance)
{
}
double Account::getBalance(){
return balance;
}
void Account::deposit(double amt){
balance += amt;
}
void Account::withdraw(double amt){
balance -= amt;
}
Customer.h
#ifndef CUSTOMER_H
#define CUSTOMER_H
#include "Account.h"
#include <iostream>
#include <string>
using namespace std;
class Customer
{
public:
Customer(string first_Name, string last_Name) :
firstName(first_Name), lastName(last_Name)
{
}
//Customer(string first_Name, string last_Name);
string getFirstName();
string getLastName();
Account getAccount();
void setAccount(Account acc);
private:
string firstName;
string lastName;
Account account;
};
#endif // CUSTOMER_H
Customer.cpp
#include "Customer.h"
#include <iostream>
#include <string>
using namespace std;
string Customer::getFirstName(){
return firstName;
}
string Customer::getLastName(){
return lastName;
}
Account Customer::getAccount(){
return account;
}
void Customer::setAccount(Account acc)
{
account = acc;
}
main.cpp
#include "Account.h"
#include "Customer.h"
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
Customer *customer;
Account account(0.0);
// Create an account that can has a 500.00 balance.
cout << endl << "Creating the customer Jane Smith.";
customer = new Customer("Jane", "Smith");
cout << endl << "Creating her account with a 500.00 balance.";
customer->setAccount(Account(500.00));
account = customer->getAccount();
cout << endl << "Withdraw 150.00";
account.withdraw(150.00);
cout << endl << "Deposit 22.50";
account.deposit(22.50);
cout << endl << "Withdraw 47.62";
account.withdraw(47.62);
// Print out the final account balance
cout << endl
<< "Customer ["
<< customer->getLastName()
<< ", "
<< customer->getFirstName()
<< "] has a balance of "
<< account.getBalance()
<< endl;
delete customer;
Account acc1(100), acc2(200);
double suAcc = acc1.getBalance()+ acc2.getBalance();
Account sumAcc(suAcc);
cout << "Balance of sumAcc is " << sumAcc.getBalance() << endl;
return (EXIT_SUCCESS);
}
Here is the error:
/cygdrive/c/Users/James/CLionProjects/untitled13/main.cpp:9: undefined reference to `Account::Account(double)'
/cygdrive/c/Users/James/CLionProjects/untitled13/main.cpp:9:(.text+0x2f): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `Account::Account(double)'
/cygdrive/c/Users/James/CLionProjects/untitled13/main.cpp:15: undefined reference to `Account::Account(double)'
/cygdrive/c/Users/James/CLionProjects/untitled13/main.cpp:15:(.text+0x12e): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `Account::Account(double)'
/cygdrive/c/Users/James/CLionProjects/untitled13/main.cpp:15: undefined reference to `Customer::setAccount(Account)
'
It goes on with every method.
I was able to compile this after making several changes.
Remove using namespace std from customer.h. It's bad practice to use "using namespace" here as it could cause name collisions when another file includes customer.h. As a result of removing "using namespace std" you'll need to qualify all of your strings as std::string instead of string.
You declared a default constructor for Account but there is no implementation provided. When a customer is created it tries to call the default constructor of account. If you are on a newer version of c++ you can change this line in your header file.
Account();
to
Account() = default;
If you're on an older version add this to Account.cpp
Account(){}
Struct Problem 1.cpp
// Struct Problem 1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include "structs.h"
double calculateEarnings(Advertising aDay);
void displayEarnings(int questionInstance, Advertising aDay);
void mainQuestions();
int _tmain(int argc, _TCHAR* argv[])
{
mainQuestions();
return 0;
}
double calculateEarnings(Advertising aDay)
{
std::cout << aDay.usersClicked; //debug
return aDay.totalAdsShown * aDay.usersClicked * aDay.averagePerAd;
}
void takeInData(int questionInstance, Advertising aDay)
{
if (questionInstance == 0)
{
std::cin >> aDay.totalAdsShown;
}
else
if (questionInstance == 1)
{
std::cin >> aDay.usersClicked;
}
else
if (questionInstance == 2)
{
std::cin >> aDay.averagePerAd;
}
std::cin;
}
void mainQuestions()
{
static Advertising aToday;
aToday.totalAdsShown = 0;
aToday.usersClicked = 0.00;
aToday.averagePerAd = 00.00;
std::cout << "Welcome! Please input the advertising data for today." << "\n";
std::cout << "How many ads were shown today?" << "\n";
takeInData(0, aToday);
std::cout << "What percentage of users clicked our ads? (decimal form)" << "\n";
takeInData(1, aToday);
std::cout << "What were the average earnings per ad? (ex: 5.15)" << "\n";
takeInData(2, aToday);
structs.h
#ifndef STRUCTS_H
#define STRUCTS_H
typedef double percentage;
typedef double USD;
struct Advertising
{
int totalAdsShown;
percentage usersClicked;
USD averagePerAd;
};
#endif
Basically, the data is not saved when called by 'cin'. I added a line to print the aDay.usersClicked value and it prints to 0. I am learning c++, so the problem is very basic. I appreciate all tips!
Thank you
Change this:
void takeInData(int questionInstance, Advertising aDay)
into this:
void takeInData(int questionInstance, Advertising& aDay)
and it will work. The reason is that in your version, the paramater aDay is passed-by-value; i.e. a copy of the argument is passed to the function. So anything that takeInData() does to its version of aDay is done in the copy. After takeInData() returns, the copy (and the information therein) is lost.
In the edited version, a reference to aDay is passed to the function. Now it will reference the variable that was passed, i.e. the variable in main(). Now all things takeInData() does, are stored in the value that is actually declared in main().
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 .
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