G++ undefined reference to class::function [duplicate] - c++

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

Related

C++: Undefined Reference to 'CYourClass::Method()' [duplicate]

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)

Palindrome programming challenge with 2 error s [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 1 year ago.
cpp
#include <iostream>
#include <stack>
#include <string>
using namespace std;
class Pstring : public string
{
public:
Pstring(string revWrd);
bool isPalindrome(string ip);
};
bool isPalindrome(string revWrd)
{
int test;
int left = 0;
int right = revWrd.size()-1;
int length = left;
while (test != length)
{
test++;
if ((revWrd[left] != revWrd[right]))
return false;
else
return true;
left++;
--right;
}
}
int main()
{
string word;
bool palindrome;
Pstring palindromeTested(word);
cout << "Enter a word or sentence to have it\n";
cout << "reversed and tested if it is a palindrome: ";
getline(cin, word);
palindrome = palindromeTested.isPalindrome(word);
if(palindrome==true)
cout<<"This is a palindrome"<<endl;
else
cout <<"That was not a palindrome";
return 0;
}
i get 2 error codes which are 1 "undefined reference to `Pstring::Pstring(std::__cxx11::basic_string, std::allocator >)'|"
and
2 "undefined reference to `Pstring::isPalindrome(std::__cxx11::basic_string, std::allocator >)'|
The error is because the member functions in the class Pstring are not defined.
The class doesn't seem used effectively, so you should remove that.
Also there are some other errors:
The variable test is used without being initialzed.
return true; is in wrong place, making strings like abcda be judged as palindrome.
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool isPalindrome(string revWrd)
{
int test = 0; // initialize test
int left = 0;
int right = revWrd.size()-1;
int length = left;
while (test != length)
{
test++;
if ((revWrd[left] != revWrd[right]))
return false;
// else
// don't return here to check all parts of the string
left++;
--right;
}
return true; // return at end of funciton
}
int main()
{
string word;
bool palindrome;
cout << "Enter a word or sentence to have it\n";
cout << "reversed and tested if it is a palindrome: ";
getline(cin, word);
palindrome = isPalindrome(word);
if(palindrome==true)
cout<<"This is a palindrome"<<endl;
else
cout <<"That was not a palindrome";
return 0;
}

C++11 Undefined reference to function

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"

Error compiling c++ tutorial (programmingHelp.org)

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

"undefined reference" error with namespace across multiple files

I've looked at several related posts but no luck with this error.
I receive this undefined reference error message below when my namespace exists across multiple files. If I compile only ConsoleTest.cpp with contents of Console.cpp dumped into it the source compiles.
I would appreciate any feedback on this issue, thanks in advance.
g++ Console.cpp ConsoleTest.cpp -o ConsoleTest.o -Wall
/tmp/cc8KfSLh.o: In function `getValueTest()':
ConsoleTest.cpp:(.text+0x132): undefined reference to `void Console::getValue<unsigned int>(unsigned int&)'
collect2: ld returned 1 exit status
Console.h
#include <iostream>
#include <sstream>
#include <string>
namespace Console
{
std::string getLine();
template <typename T>
void getValue(T &value);
}
Console.cpp
#include "Console.h"
using namespace std;
namespace Console
{
string getLine()
{
string str;
while (true)
{
cin.clear();
if (cin.eof()) {
break; // handle eof (Ctrl-D) gracefully
}
if (cin.good()) {
char next = cin.get();
if (next == '\n')
break;
str += next; // add character to string
} else {
cin.clear(); // clear error state
string badToken;
cin >> badToken;
cerr << "Bad input encountered: " << badToken << endl;
}
}
return str;
}
template <typename T>
void getValue(T &value)
{
string inputStr = Console::getLine();
istringstream strStream(inputStr);
strStream >> value;
}
}
ConsoleTest.cpp
#include "Console.h"
void getLineTest()
{
std::string str;
std::cout << "getLinetest" << std::endl;
while (str != "next")
{
str = Console::getLine();
std::cout << "<string>" << str << "</string>"<< std::endl;
}
}
void getValueTest()
{
std::cout << "getValueTest" << std::endl;
unsigned x = 0;
while (x != 12345)
{
Console::getValue(x);
std::cout << "x: " << x << std::endl;
}
}
int main()
{
getLineTest();
getValueTest();
return 0;
}
The template function needs to be defined, not only declared, in the header. The compiler needs to see the template implementation and the template argument to build the specialization you require in your main. So put the definition in the header directly:
namespace Console
{
std::string getLine();
template <typename T>
inline void getValue(T &value) {
string inputStr = Console::getLine();
istringstream strStream(inputStr);
strStream >> value;
}
}