I just got into C++ and I was trying to write a simple code for a simulation, but I bumped into a multiple definition problem than I cannot solve.
So, I'm creating a class and this is the header file:
Piano.h
#ifndef PIANO_H
#define PIANO_H
#include"vettore.h"
#include"PuntoMat.h"
#include<string>
#include<vector>
class Piano
{
public:
//Costruttori
Piano(std::string material, float lenght, float inclin = 0)
: m_material(material), m_lenght(lenght), m_inclin(inclin), m_time(0) {;}
//Metodo per l'aggiunta di corpi al piano
void Add(PuntoMat p) { m_corpi.push_back(&p); }
//Metodo che stampa le coordinate dei corpi nel sistema
void Print();
private:
std::string m_material;
std::vector<PuntoMat*> m_corpi;
float m_lenght;
float m_inclin;
float m_time;
};
#endif
this is the corresponding file .cxx, where I define the function "Print"
Piano.cxx
#include"vettore.h"
#include"PuntoMat.h"
#include"Piano.h"
#include<iostream>
#include<stdlib.h>
#include<vector>
void Piano::Print()
{ std::cout << "Tempo: " << m_time << " s" << std::endl;
if(m_corpi.size() == 0)
{ std::cout << "Nessun corpo sul piano" << std::endl;
exit(1);
}
for(int i=0; i<m_corpi.size(); i++)
{ std::cout << *m_corpi[i] << std::endl;
}
std::cout << std::endl;
}
This is the code I'm using to validate the class
main.cxx
#include<iostream>
#include"vettore.h"
#include"PuntoMat.h"
#include"Piano.cxx"
#include<string>
main()
{
PuntoMat a(3, Vettore( 0, 0), Vettore( 5.4, 0), "Legno");
PuntoMat b(5, Vettore( 8.3, 6.5), Vettore( 0, 0), "Vetro");
Piano p( "Ferro", 50);
p.Add(a);
p.Add(b);
p.Print();
return 0;
}
When I compile I get a multiple definition error about the function Print, this one:
/tmp/ccp1giKM.o: In function `Piano::Stampa()':
main.cxx:(.text+0x0): multiple definition of `Piano::Stampa()'
/tmp/cctCJRQF.o:Piano.cxx:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
I really don't know how to solve this problem, since it seems to me that the function Print() has been defined only in the file Piano.cxx. Can anyone help me with this?
P.s. Ignore the general meaning of the code and the comments (they are in italian). All the other classes included have been already validate and there is no problem with them.
Piano::Stampaanywhere in your code. Please check if you posted the right code. - DYZ.cxxfile. You compile that to a.ofile, and link it withmain.o. - Barmar