g++ error: undefined reference while netbeans compiles in linux [duplicate] - c++

This question already has answers here:
"undefined reference to" using 'g++' to compile a C++ program
(3 answers)
Closed 9 years ago.
Im using NetBeans IDE in linux mint for C++ programming. NetBeans compiles the code just fine but when i try to compile the main.cpp using g++ as in g++ main.cpp i get undefined reference errors:
I know there are many questions like this one and they the problem can be fixed by using the right -l library but I couldn't find any related to NetBeans/g++ and I couldn't figure how to overcome this problem.
Any help is appreciated.
Errors:
tmp/ccXSo5xI.o: In function `main':
main.cpp:(.text+0x82): undefined reference to `Hospital::Hospital(int, int, int)'
main.cpp:(.text+0xf3): undefined reference to `Resident::Resident(int, int)'
.
.
.
main.cpp
#include <iostream>
#include <cstdio>
#include "Resident.h"
#include "Hospital.h"
#include <stack>
using namespace std;
void readFromFiles(int [][10], int [][10]);
void readFromFiles(Hospital*[10], Resident*[10]);
void print10(int [][10], int [][10]);
void print10(Hospital*[10], Resident*[10]);
int main(void) {
int hospital[10][10] = {0};
int resident[10][10] = {0};
Hospital **hospitals = new Hospital*[10];
for(int i = 0 ; i < 10 ; i++)
hospitals[i] = new Hospital(3, i, 10); //3: quota, i: hospital number, 10:prefereneceLength
Resident **residents = new Resident*[10];
for(int i = 0 ; i < 10 ; i++)
residents[i] = new Resident(i,10); //i: hospital number, 10:prefereneceLength
.
.
.
Hospital.h
#ifndef HOSPITAL_H
#define HOSPITAL_H
#include "Resident.h"
using namespace std;
class Hospital {
public:
//constructors & destructors
Hospital();
Hospital(const int, const int, const int);
Hospital(const Hospital& orig);
virtual ~Hospital();
//getters & setters
int getNumber();
int getQuota();
int** getPreferenceList();
//member functions
void addPreference(const int, const int);
private:
int number;
int* preferenceList[2]; //1st row: preference order ; 2nd row: admission status
int quota;
Resident *admittedResidents;
};
#endif /* HOSPITAL_H */
Resident.h
#ifndef RESIDENT_H
#define RESIDENT_H
class Resident {
public:
//constructors & destructors
Resident();
Resident(const int, const int);
Resident(const Resident& orig);
virtual ~Resident();
//getters, setters
int getNumber();
int* getPreferenceList();
bool getAdmissionStatus();
//member functions
void addPreference(const int, const int);
private:
int number; //resident number
int proposalCount;
int* preferenceList; //not inverse, unlike Hospitals pref list
bool admissionStatus;
};
#endif /* RESIDENT_H */
I know that's a lot of code even though I shortened them, but I think they are the necessary parts. Thanks.

You need to include all source files:
g++ main.cpp hospital.cpp resident.cpp

g++ main.cpp will try to compile and link main.cpp into an executable (a.out). In the link stage, ld is not finding the symbols for the Hospital and Resident constructors while are called in main.cpp because they have not yet been compiled.
If you just want to compile main.cpp, use:
g++ -c main.cpp
You can link the object files later using:
g++ main.o hospital.o resident.o
If you want to compile and link the whole lot:
g++ main.cpp hospital.cpp resident.cpp

Related

How to inherit from an abstract class properly in C++?

I couldn't find a proper topic for this question as I haven't got a proper error message.
I'm trying to create a management system for a restaurant which mainly provides pizza as well as other foods(pasta, wings, etc). I want this system to be used by the staff. I have created an abstract class named Foods that can be used to inherit by other foods. So far I have created a class that inherits from Foods named Pizza. Below are my code.
PS: I have used namespaces for organize foods and staff members separately. As far as I know some people doesn't recommend namespace and my apologies if you're one of them.
interfaces.h
#include <vector>
#include <string>
namespace foods{
class Food{
double price;
// since the sauces and drinks are given with foods.
static const std::vector<std::string> sauces;
static const std::vector<std::string> drinks;
public:
virtual int retPrice() = 0;
virtual void ask() = 0; // ask user what to add
virtual ~Food() = default;
};
const std::vector<std::string> Food::sauces = {"Blue cheese", "Garlic", "Honey BBQ", "Marinara"};
const std::vector<std::string> Food::drinks = {"Pepsi", "Mountain Dew", "Coca Cola"};
class Pizza: public Food{
const double price;
const std::string pizzaType; // whether it is chicken, beef, etc.
const std::string size; // small, medium or large
int crust = 1; // how crust it is from 1-5
std::vector<std::string> toppings; // to store toppings
public:
Pizza(): price(15), pizzaType(" "), size(" "){}
int retPrice() override; // the price should change according to the type
void ask() override; // ask the customer for a pizza
void createACustom(); // create a custom pizza with desired toppings
};
};
functions.cpp
#include <iostream>
#include "interfaces.h"
namespace foods{
int Pizza::retPrice(){
return (price+5);
}
void Pizza::ask(){
std::cout << "Hello World!";
}
}
test.cpp
#include "interfaces.h"
int main(){
foods::Pizza* pizza = new foods::Pizza();
}
And I'm getting following error.
/usr/bin/ld: /tmp/ccQRR5B8.o: warning: relocation against `_ZTVN5foods5PizzaE' in read-only section `.text._ZN5foods5PizzaC2Ev[_ZN5foods5PizzaC5Ev]'
/usr/bin/ld: /tmp/ccQRR5B8.o: in function `foods::Pizza::Pizza()':
test.cpp:(.text._ZN5foods5PizzaC2Ev[_ZN5foods5PizzaC5Ev]+0x2b): undefined reference to `vtable for foods::Pizza'
/usr/bin/ld: warning: creating DT_TEXTREL in a PIE
collect2: error: ld returned 1 exit status
I tried using the keyword override and also made a default deconstructor, yet nothing seems working. I want to know what this error message means and a solution for this. In addition to that what is vtable?
Appreciate your time and answers.
EDIT 1
I have compiled it with g++ -Wall -Wextra test.cpp functions.cpp -o test, which is wrong and then I did g++ -Wall -Wextra test.cpp functions.cpp -o test and I'm getting following error.
/usr/bin/ld: /tmp/ccmv2G17.o:(.bss+0x0): multiple definition of `foods::Food::sauces[abi:cxx11]'; /tmp/ccuBNQjX.o:(.bss+0x0): first defined here
/usr/bin/ld: /tmp/ccmv2G17.o:(.bss+0x20): multiple definition of `foods::Food::drinks[abi:cxx11]'; /tmp/ccuBNQjX.o:(.bss+0x20): first defined here
collect2: error: ld returned 1 exit status
Why is it saying that it has multiple definitions?
You need to implement the static member variables sauces and drinks in functions.cpp and not in interfaces.h.
functions.cpp
namespace foods {
int Pizza::retPrice() {
return (price + 5);
}
void Pizza::ask() {
std::cout << "Hello World!";
}
// implement the static variables here.
const std::vector<std::string> Food::sauces = { "Blue cheese", "Garlic", "Honey BBQ", "Marinara" };
const std::vector<std::string> Food::drinks = { "Pepsi", "Mountain Dew", "Coca Cola" };
}
And remove them from interfaces.h.
If you implement them in interfaces.h they end up being implemented in each .cpp file that includes interfaces.h.
It's basically the same problem as if you define a global variable in a .h file.

How to tell g++ to use stuff from .lib file?

I am trying to compile a C++ using g++ in Linux which uses some functions defined in a header file crated by someone. I am not much experienced with C++ so I am not sure how to proceed (or even if I understand what should be done).
I have all these files in a single directory:
PaLaser.cxx, this is the main.
USBM3.h
hidapi.h
hidapi.lib
hidapi.dll
USBM3.lib
USBM3.dll
This was created by someone for Windows and now I want to compile for Linux. The USBM3.h looks like this:
#include <sstream>
#include <string.h>
using namespace std;
class HIDDLL
{
private:
static void init();
static void SendDataToUSB();
static int parseChar(unsigned char );
static void ParseByte(string);
static int openFile(char *);
static void SendFile();
static void readADC();
public:
/* This method is used to generate sequence */
static __attribute__((visibility("default"))) void seqMODE(int mode);
/* This method is used to turn off LASER */
static __attribute__((visibility("default"))) void LASERTurnOff(void);
/* This method is used to send freq data to ARM */
static __attribute__((visibility("default"))) void sendFreq(int freq);
bla bla bla
};
and in the PaLaser.cxx there is this:
#include "hidapi.h"
#include "USBM3.h"
#pragma comment(lib, "USBM3.lib")
When I run
g++ PaLaser.cxx -o PaLaser
I get
/usr/bin/ld: /tmp/ccUXpAbN.o: in function `main':
PaLaser.cxx:(.text+0x1e): undefined reference to `HIDDLL::isDeviceAttached()'
/usr/bin/ld: PaLaser.cxx:(.text+0x33): undefined reference to `HIDDLL::readLASERstate()'
.............
where ........... stands for all the things defined in USBM3.h.
I have no certainty whether these things are packed within the USBM3.lib file, but I hope they are. How do I tell g++ to look there?

Why do I get an Undefined reference error when trying to compile? [duplicate]

This question already has answers here:
Separating class code into a header and cpp file
(8 answers)
Closed 1 year ago.
Just had a little problem that I haven't been able to figure out yet.
I was using a similar program structure for a different project, but the problem boils down to this. I have two cpp files, which are:
Trading_dte.cpp :
#include <iostream>
using namespace std;
class Dte
{
public:
int addition(int a, int b)
{
return a + b;
}
};
dummy.cpp :
#include <iostream>
#include "Trading_dte.hpp"
Dte obj;
int check()
{
std::cout<<obj.addition(6,9);
}
I created a header file called Trading_dte.hpp :
# pragma once
#include <iostream>
class Dte
{
public:
int addition(int a, int b);
};
Now when I try compiling using the command :
g++ Trading_dte.cpp dummy.cpp
I get the error :
/usr/bin/ld: /tmp/ccCcM8R6.o: in function `check':
dummy.cpp:(.text+0x1a): undefined reference to `Dte::addition(int, int)'
collect2: error: ld returned 1 exit status
I'm sure it's something small, but I just can't figure what.
Thanks a lot in advance!
your cpp file need to be written differently
#include "Trading_dte.hpp"
#include <iostream>
int Dte::addition(int a, int b)
{
return a + b;
}
You've created two separate Dte classes, one visible to main and another visible only in Trading_dte.cpp. The one visible to main, defined in Trading_dte.hpp has a declaration of the addition member function but no definition.
Probably the easiest thing to do is to drop Trading_dte.cpp and put the implementation into the class definition in Trading_dte.hpp.
Trading_dte.hpp:
# pragma once
class Dte
{
public:
int addition(int a, int b)
{
return a + b;
}
};
Note that I also removed the #include <iostream> line. You don't need it in the header file because you don't use it in the class.

linking hpp and cpp issues with g++ compiler

I am relatively new to c++ and have a solid C and Object Oriented background. So I have the following code written.
I have Person.hpp which is as follows:
class Person
{
private:
struct h
{
char *name;
unsigned char age;
};
struct h entities;
public:
unsigned char age();
char *name();
Person(char *name, unsigned char a);
~Person();
};
The Person.cpp looks as follows:
#include "Person.hpp"
char *Person::name()
{
return entities.name;
}
unsigned char Person::age()
{
return entities.age;
}
Person::Person(char *name, unsigned char a)
{
entities.name = name;
entities.age = a;
}
And finally main.cpp looks like the following:
#include <iostream>
#include "Person.hpp"
int main()
{
Person someone("something", 100);
printf("%s is %d old\n", someone.name(), someone.age());
return 0;
}
I am already aware of the warning that it will cause due to the fact that the string is not constant. This will not cause an error when trying to compile. I tried compiling the code in two different methods. One by just compiling all together which would look like the following:
g++ -o main main.cpp Person.cpp
And the second method I tried was to compile them into object files and then link them together:
g++ -c main.cpp
g++ -c Person.cpp
g++ -o main main.o Person.o
They both give the following error:
/usr/bin/ld: main.o: in function `main':
main.cpp:(.text+0x5b): undefined reference to `Person::~Person()'
/usr/bin/ld: main.cpp:(.text+0x6e): undefined reference to `Person::~Person()'
collect2: error: ld returned 1 exit status
Any help would be greatly appreciated.
You have a destructor declared here in your header file:
public:
unsigned char age();
char *name();
Person(char *name, unsigned char a);
~Person(); // <===== Declared here
But you haven't provided any definitions for it.
However, the destructor is called after your main function returns (you can learn more about this behavior here), so it needs a definition.
You can make the compiler generate the definition for you by either omitting the destructor declaration or use ~Person() = default.
The problem is that you declare both an constructor and destructor in Person.hpp, but only define the constructor in the Person.cpp file.
Try add the following code to Person.cpp:
Person::~Person()
{
}

can't use separate function files in eclipse

I am trying to declare the functions in separate files. In the code given below, my main() is defined in main.cpp and the int addition(int x, int y) is defined
in an another file named function.cpp.
My code:
main.cpp
#include "function.cpp"
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int b = 15;
int sum = addition(a,b);
cout<<"\nSum = "<<sum<<"\n";
return 0;
}
fucntion.cpp
int addition(int x, int y)
{
int sum = x + y;
return sum;
}
But by using the above cod in Eclipse i am getting the following error. On the other hand, if i compile the code manually using make
through the linux terminal then, the same got works.
ERROR:
/home/eclipse_workspace/multiFiles/Debug/../funtion.cpp:9: multiple definition of `addition(int, int)'
./funtion.o:/home/eclipse_workspace/multiFiles/Debug/../funtion.cpp:9: first defined here
collect2: ld returned 1 exit status.
First of all it is not recommended to include .cpp files. You should create header (.h) with declarations, put implementations to .cpp, like now and wherever you need to use it just include.h . You should also read about avoiding multiple includes by adding #ifndef/#define/#endif.
Update:
#include works in pre compiling phase and more or less it means "paste here what you have in file ...". So it copies function from one file and pastes to main file then compiles it. After this it compiles also cpp file with your function - also ok. Now comes linking: because of previous steps and copy-paste it has two definitions (actually two symbols) which has same name - that is causing the error and that's why we have headers :)
First create a header file, for example Addition.h and declare the function name inside it. Then make a file Addition.cpp and write the addition function implementation and then include the Addition.h in your main.cpp file.
The concept of using a header file is that you can use it anywhere else and is not limited to your main.cpp program file.
So, in short
Addition.h
class Addition { public:
int addition(int a , int b); //function declaration
private: int result_; };
then in Addition.cpp
#include Addition.h
int Addition::addition(int x, int y) {
// function implementation
}
in main.cpp
#include <Addition.h>
int main()
{ int a=3, b=4, sum=0;
Addition objAdd; //creation of object for class Addition
sum = objAdd.addition(a,b);
}
Hope this helps in structuring your code.