Multiple definition of error linking my library - c++

i'm trying to create a library with some functions I often use, but compiling I have this error:
Torri_lib.cpp||multiple definition of `inizRandVett(int*, int, int, int)'|
Torri_lib.cpp||first defined here|
Torri_lib.cpp||multiple definition of `printVett(int*, int)'|
Torri_lib.cpp||first defined here|
Torri_lib.cpp||multiple definition of `scambio(int*, int*)'|
Torri_lib.cpp||first defined here|
||=== Build finished: 6 errors, 0 warnings (0 minutes, 0 seconds) ===|
This is the main.cpp:
#include <iostream>
#include "Torri_lib.h"
#define N 10
using namespace std;
void ordina(int*,int);
int main()
{ int vett[N];
srand(time(NULL));
inizRandVett(vett,N,-20,20);
printf("Vettore generato:\n");
printVett(vett,N);
ordina(vett,N);
printf("\n\nVettore ordinato (neg a sx, pos a dx):\n");
printVett(vett,N);
printf("\n\n");
return 0;
}
void ordina(int*vett,int dim)
{ int i,j,neg=0,pos=0;
for(i=0;i<dim;i++)
if(vett[i]<0)
neg++;
else
pos++;
for(i=0,j=neg;i<neg;i++)
if(vett[i]>=0){
while(vett[++j]>=0);
scambio(&vett[i],&vett[j]);
}
}
This is Torri_lib.cpp:
#include <iostream>
#include"Torri_lib.h"
void inizRandVett(int *vett, int dim, int rangeMin, int rangeMax)
{ int i;
for(i=0;i<dim;i++)
vett[i]=rand()%(rangeMax-rangeMin)+rangeMin;
}
void printVett(int *vett, int dim)
{ int i;
for(i=0;i<dim;i++)
printf("%d ",vett[i]);
}
void scambio(int*var1,int*var2)
{
int temp=*var1;
*var1=*var2;
*var2=temp;
}
And this is Torri_lib.h :
void inizRandVett(int*, int, int, int );
void printVett(int *, int);
void scambio(int*,int*);
I don't understand why it says me this error, I don't see multiple definition of the functions.
Can you help me? Thanks!

Maybe you didn't put a guard in your .h file?
Try putting at the beginning of the file:
#ifndef TORRI_H_INCLUDED
#define TORRI_H_INCLUDED
and at the end:
#endif

You need to write in header file to prevent multiple declaration:
#pragma once
// code
OR
#ifndef NAME_H_
# define NAME_H_
// code
#endif

Related

Why is my c++ singleton not working on Clion?

I want to have a singleton in my project but some errors occur
this is my codes in three separate files.:
//---------------My main.cpp code
#include <iostream>
#include "Sports/BBVB.h"
int main() {
bbvb;
return 0;
}
// ---------------------------my BBVB.h code
#ifndef SAMAVAR_BBVB_H
#define SAMAVAR_BBVB_H
typedef struct VBResult{
int set1=-1;
int set2=-1;
int set3=-1;
int set4=-1;
int set5=-1;
}VBResult;
#include "Sport.h"
#include "../TournamentStuf/Tournament.h"
class BBVB: public Sport {
protected:
vector<Tournament<VBResult>> tours;
public:
static BBVB& getInstance(){
static BBVB b;
return b;
}
private:
BBVB(){}
public:
BBVB(BBVB const&)=delete;
void operator=(BBVB const&) = delete;
//-------------Setter------------
//------------Getter-------------
vector<Tournament<VBResult>> getTours() const;
Tournament<VBResult> getTourById(int id) const;
//----------Others---------------
void addTour(Tournament<VBResult> v);
};
BBVB &bbvb=BBVB::getInstance();
#endif //SAMAVAR_BBVB_H
//------------------my Store and restore code
#ifndef SAMAVAR_STOREANDRESTORE_H
#define SAMAVAR_STOREANDRESTORE_H
#include "../Sports/BBVB.h"
#include "../Sports/PingPong.h"
#include "../Sports/Wrestling.h"
void Start(BBVB &b);
void Update(const BBVB &b);
void Start(PingPong &p);
void Update(const PingPong &p);
void Start(Wrestling &w);
void Update(const Wrestling &w);
#endif //SAMAVAR_STOREANDRESTORE_H
I have a bbvb instance of BBVB but it says you have multiple definitions of it.
I'm new to Clion and I don't have enough information about somethings like cmake and I feel the problem is because of it.
I want to have something like cout and cin in iostream.so by including my BBVB I can access this object.
Clion shows error below:
CMakeFiles\Samavar.dir/objects.a(BBVB.cpp.obj):BBVB.cpp:(.bss+0x0): multiple definition of `bbvb'
CMakeFiles\Samavar.dir/objects.a(main.cpp.obj):main.cpp:(.bss+0x0): first defined here
CMakeFiles\Samavar.dir/objects.a(StoreAndRestore.cpp.obj):StoreAndRestore.cpp:(.bss+0x0): multiple definition of `bbvb'
CMakeFiles\Samavar.dir/objects.a(main.cpp.obj):Samavar-master/Sports/BBVB.h:24: first defined here
collect2.exe: error: ld returned 1 exit status

I'm getting a linkage error [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 5 years ago.
I've applied all the solutions provided by you for similar problems but I'm still getting this error:
undefined reference to `setgolf(golf&, char*, int)'
collect2: error: ld returned 1 exit status
here is the code header
#ifndef SANS_H_INCLUDED
#define SANS_H_INCLUDED
const int len = 40;
struct golf
{
char fullname[len];
int handicap;
};
//void setgolf(golf &,char * ,int);
int setgolf(golf &);
void sethandicap(golf &,int );
void showgolf(const golf &);
#endif
here is the file containing the functions definitions
#include <iostream>
#include <cstring>
#include "chapter9exe3.h"
void setgolf(golf & s,char *c ,int hc)
{
strcpy(s.fullname,c);
s.handicap=hc;
}
int setgolf(golf & s)
{
std::cin.getline(s.fullname,len);
if(s.fullname[0] == '\0'&& s.fullname[1] == '\0' && s.fullname[2] == '\0')
return 0;
else
return 1;
}
void sethandicap(golf & s,int n )
{
s.handicap = n;
}
void showgolf(const golf & s)
{
std::cout<<"the full name :"<<s.fullname<<std::endl;
std::cout<<"the handcape :"<<s.handicap<<std::endl;
}
here is the file containing the main function
#include <iostream>
#include "sans.h"
int main()
{
golf player;
char name[len] = "santers God's men";
int handicap = 84;
setgolf(player,name,handicap);
return 0;
}
Uncomment this:
//void setgolf(golf &,char * ,int);
in your header file, since you are doing in main:
setgolf(player,name,handicap);
which will search for a matching prototype in the header file, and will fail to fidn it, because you have commented it.
In other words, you call the function with three parameters, but only provide a prototype of this function in the header file with one parameter. As a result, the reference to setgolf() with three parameters is definetely undefined!

C++ Compiler errors

I'm writing a c++ stack and queue implementation program, I finished the stack part, but when compiling I'm getting these errors
arrayListImp.cpp:18:19: error: expected unqualified-id
arrayList[++top]= x;
^
arrayListImp.cpp:28:13: error: 'arrayList' does not refer to a value
itemPoped=arrayList[top];
^
./arrayList.h:3:7: note: declared here
class arrayList{
^
arrayListImp.cpp:35:9: error: 'arrayList' does not refer to a value
return arrayList[top];
^
./arrayList.h:3:7: note: declared here
class arrayList{
^
arrayListImp.cpp:46:9: error: 'arrayList' does not refer to a value
cout<<arrayList[i]<<endl;
^
./arrayList.h:3:7: note: declared here
class arrayList{
^
4 errors generated.
Here is the header file
#ifndef ARRAYLIST_H
class arrayList{
public:
arrayList();
static const int maxSize = 10;
int array[10];
};
class stack : public arrayList{
public:
stack();
void push(int x);
void pop();
int Top();
int isEmpty();
void print();
int x;
int top;
int itemPoped;
int i;
};
#define ARRAYLIST_H
#endif
arrayListImp.cpp
#include <iostream>
#include "arrayList.h"
using namespace std;
//Stack implementation
stack::stack(){
top = -1;
}
void stack::push(int x){
if (top == maxSize -1){
cout<<"Stack overflow"<<endl;
}
else{
arrayList[++top]= x;
cout<<x<<", is pushed on to the stack"<<endl;
}
}
void stack::pop(){
if (top == -1){
cout<<"Stack underflow"<<endl;
}
else{
itemPoped=arrayList[top];
top--;
cout<<itemPoped<<", is poped from the stack"<<endl;
}
}
int stack::Top(){
return arrayList[top];
}
int stack::isEmpty(){
if (top == -1) return 1;
return 0;
}
void stack::print(){
cout<<"Stack: "<<endl;
for (i = 0; i<=top; i++){
cout<<arrayList[i]<<endl;
}
}
arrayListUse.cpp
#include <iostream>
#include "arrayList.h"
using namespace std;
int main()
{
//Stack testing
stack S;
S.push(1);S.print();
S.push(2);S.print();
S.push(3);S.print();
S.pop();S.print();
S.push(4);S.print();
//Queue testing
return 0;
}
Can you please point out to what I'm doing wrong here?
You should just read your error messages.
You should use array instead of arrayList, which is the name of the class. So just refer to the variable instead.
The error message you got is something like
test.cpp: In member function ‘void stack::push(int)’:
test.cpp:44:18: error: expected unqualified-id before ‘[’ token
arrayList[++top]= x;
^
When you check the line, you immediately see what is wrong there.
You declare a constructor arrayList::arrayList(), but you do not define it. Either you can drop the declaration, or you should implement it in the cpp-file.
arrayList::arrayList() {
// do some initialization
}
The error message you got is something like
/tmp/cc4y06YN.o:test.cpp:function stack::stack(): error: undefined reference to 'arrayList::arrayList()'
The code could compile, but it did not link. So all declarations may be correct, but a symbol was missing. This is usually the case when you declared something you referred to, but you never defined it.
You always have written
arrayList[...]
what is the name of your class but reading the code it seems like you wanted to write
array[...]
which would access the data.

G++ - Undefined Reference to member function that is defined

I am currently working on a virtual run time environment program that is at a very early stage, i am prevented from continuing my work due to a linker error when using my makefile, provided below. The error i am receiving is:
g++ controller.o processor.o test.o -o final
controller.o: In function `Controller::run()':
controller.cpp:(.text+0x1e0): undefined reference to
Processor::codeParams(char)'
controller.o: In function `Controller::fetch()':
controller.cpp:(.text+0x290): undefined reference to `Controller::pc'
controller.cpp:(.text+0x299): undefined reference to `Controller::pc'
collect2: error: ld returned 1 exit status
makefile:16: recipe for target 'final' failed
make: *** [final] Error 1
I am unsure as to why i get this error as i thought i had defined these things in the source file corresponding to the header. All files will be given below so that the program can be compiled.
test.cpp:
#include <iostream>
#include <vector>
#include "includes/controller.h"
using namespace std;
int main()
{
vector<char> prog = {0x0};
Controller contr(prog);
cout << "Error Code: " << contr.run() << endl;
return 0;
}
controller.cpp:
/*
Author(s): James Dolan
File: controller.cpp
Build: 0.0.0
Header: includes/controller.h
DoLR: 21:39 11/1/2017
Todo: n/a
*/
#include "includes/controller.h"
Controller::Controller(vector<char> prog)
{
printf("Program:"); //Display program
for(auto i : program)
{
printf("%02X", i);
}
printf("\n");
Controller::program = program;
}
Controller::~Controller ()
{
}
int Controller::run()
{
bool runFlag = true;
int errorCode = 0;
char curCode;
vector<char> curInstr;
int paramRef;
while(runFlag)
{
curCode = fetch();
printf("curCode:%02X\n", curCode);
curInstr.push_back(curCode);
paramRef = proc.codeParams(curCode);
if (paramRef == 0xffff){runFlag = false; continue;} //Check if shutdown signal was returned, if so shutdown
printf("opcode good\n");
for(int i; i<paramRef; i++){curInstr.push_back(fetch());}
}
return errorCode;
}
char Controller::fetch()
{
return program[pc++]; //Return next instruction then increment the program counter
}
controller.h:
/*
Author(s): James Dolan
File: controller.h
Source: ../controller.cpp
DoLR: 21:39 11/1/2017
Todo: n/a
*/
#ifndef CONTROLLER_H
#define CONTROLLER_H
#include <iostream>
#include <vector>
#include <cstdlib>
#include "processor.h"
using namespace std;
class Controller{
public:
Controller(vector<char> prog);
~Controller();
int run();
protected:
private:
vector<char> program;
static int pc;
char fetch();
Processor proc();
};
#endif
processor.cpp:
#include "includes/processor.h"
Processor::Processor()
{
}
Processor::~Processor()
{
}
int codeParams(char code)
{
switch(code)
{
case 0x0: //Halt
return 0;
default:
printf("[ERROR!] Invalid opcode [%02X]", code);
return 0xffff; //Return shutdown signal
}
}
processor.h:
#ifndef PROCESSOR_H
#define PROCESSOR_H
#include <iostream>
#include <cstdlib>
class Processor{
public:
Processor();
~Processor();
int codeParams(char code);
protected:
private:
};
#endif
All if any help is appreciated massively as it will help me to continue with my passion of developing a fully fledged open-source virtual runtime enviroment like the java vm, thank you for your time.
In Controller.cpp you need a int Controller::pc; or int Controller::pc = 0;
In the header file you declared a static int named pc that exists somewhere. It needs to actually exist in a translation unit somewhere (in this case Controller.cpp) so that when the linker tries to find it... it exists.
In Processor.cpp your signature should look like int Processor::codeParams(char code) to let the compiler know that is Processor's codeParams and not a random function named codeParams that happens to also take a character.
For the member function Processor::codeParams you should define it as:
int Processor::codeParams(char code)
// ~~~~~~~~~~~
{
...
}
Otherwise it's just a normal (non–member) function.
For the static member Controller::pc you should define it outside of the class definition, in controller.cpp.
// Controller.h
class Controller {
...
private:
static int pc;
};
// controller.cpp
int Controller::pc;

Multiple definition of <List of functions>

I'm sure that the answer is staring me straight in the face, but I haven't been able to make any progress due to this... First some code:
objects/testObject.h:
#include <irrlicht.h>
#include "../maths.h"
using namespace irr;
#ifndef testObject_H
#define testObject_H
class testObject : public scene::SAnimatedMesh
{
public:
testObject(IrrlichtDevice* device);
virtual ~testObject();
protected:
const char* meshInfoLocation;
int totAnims;
private:
};
#endif
objects/testObject.cpp:
#include "testObject.h"
testObject::testObject(IrrlichtDevice* device) : scene::SAnimatedMesh()
{
io::IrrXMLReader* modelInformation = io::createIrrXMLReader(meshInfoLocation);
while(modelInformation->read())
{
if(modelInformation->getNodeName() == "totAnims") totAnims = stringToInt(modelInformation->getAttributeValue("totAnims"));
}
}
testObject::~testObject() { } //Incomplete, but should still compile...
When I compile this code, I get the following errors:
/home/david/workspace/spaceSim/objects/testObject.cpp||In constructor ‘testObject::testObject(irr::IrrlichtDevice*)’:|
/home/david/workspace/spaceSim/objects/testObject.cpp|20|warning: comparison with string literal results in unspecified behaviour [-Waddress]|
/home/david/workspace/spaceSim/main.cpp||In function ‘int main(int, char**)’:|
/home/david/workspace/spaceSim/main.cpp|24|warning: ‘virtual bool irr::io::IFileSystem::addZipFileArchive(const c8*, bool, bool)’ is deprecated (declared at /home/david/irrlicht-1.8.1/include/IFileSystem.h:228) [-Wdeprecated-declarations]|
/home/david/workspace/spaceSim/objects/testObject.cpp||In constructor ‘testObject::testObject(irr::IrrlichtDevice*)’:|
/home/david/workspace/spaceSim/objects/testObject.cpp|20|warning: comparison with string literal results in unspecified behaviour [-Waddress]|
obj/Debug/objects/testObject.o||In function `testObject::testObject(irr::IrrlichtDevice*)':|
/home/david/workspace/spaceSim/objects/testObject.cpp|3|multiple definition of `testObject::testObject(irr::IrrlichtDevice*)'|
obj/Debug/main.o:/home/david/workspace/spaceSim/objects/testObject.cpp|3|first defined here|
obj/Debug/objects/testObject.o||In function `testObject::testObject(irr::IrrlichtDevice*)':|
/home/david/workspace/spaceSim/objects/testObject.cpp|3|multiple definition of `testObject::testObject(irr::IrrlichtDevice*)'|
obj/Debug/main.o:/home/david/workspace/spaceSim/objects/testObject.cpp|3|first defined here|
obj/Debug/objects/testObject.o||In function `testObject::~testObject()':|
/home/david/workspace/spaceSim/objects/testObject.cpp|27|multiple definition of `testObject::~testObject()'|
obj/Debug/main.o:/home/david/workspace/spaceSim/objects/testObject.cpp|27|first defined here|
obj/Debug/objects/testObject.o||In function `testObject::~testObject()':|
/home/david/workspace/spaceSim/objects/testObject.cpp|27|multiple definition of `testObject::~testObject()'|
obj/Debug/main.o:/home/david/workspace/spaceSim/objects/testObject.cpp|27|first defined here|
obj/Debug/objects/testObject.o||In function `virtual thunk to testObject::~testObject()':|
/home/david/workspace/spaceSim/objects/testObject.cpp|29|multiple definition of `virtual thunk to testObject::~testObject()'|
obj/Debug/main.o:/home/david/workspace/spaceSim/objects/testObject.cpp|29|first defined here|
obj/Debug/objects/testObject.o||In function `testObject::~testObject()':|
/home/david/workspace/spaceSim/objects/testObject.cpp|27|multiple definition of `testObject::~testObject()'|
obj/Debug/main.o:/home/david/workspace/spaceSim/objects/testObject.cpp|27|first defined here|
obj/Debug/objects/testObject.o||In function `virtual thunk to testObject::~testObject()':|
/home/david/workspace/spaceSim/objects/testObject.cpp|29|multiple definition of `virtual thunk to testObject::~testObject()'|
obj/Debug/main.o:/home/david/workspace/spaceSim/objects/testObject.cpp|29|first defined here|
||=== Build finished: 14 errors, 3 warnings ===|
I've tried the following at solving:
Combining the header and the cpp files.
Emptying out all the method bodies and removing the #includes so that all that matters is the class structure.
Google searches (without any luck...)
Thank you for the help!
I compiled your code using gcc4.8.1 from mingw32 (www.mingw.org) (putting them into file, and replacing missing types). The compilation seems to be OK. I guess the problem could be
#include <irrlicht.h>
#include "../maths.h"
code:
//#include <irrlicht.h>
//#include "../maths.h"
//using namespace irr;
#ifndef testObject_H
#define testObject_H
#include <tuple>
namespace scene {
typedef std::tuple<int,int> SAnimatedMesh;
};
typedef int IrrlichtDevice;
class testObject : public scene::SAnimatedMesh
{
public:
testObject(IrrlichtDevice* device);
virtual ~testObject();
protected:
const char* meshInfoLocation;
int totAnims;
private:
};
#endif
//#include "testObject.h"
testObject::testObject(IrrlichtDevice* device) : scene::SAnimatedMesh()
{
/*
io::IrrXMLReader* modelInformation = io::createIrrXMLReader(meshInfoLocation);
while(modelInformation->read())
{
if(modelInformation->getNodeName() == "totAnims") totAnims = stringToInt(modelInformation->getAttributeValue("totAnims"));
}
*/
}
testObject::~testObject() { } //Incomplete, but should still compile...
int main() {}