Listed below are my four separate files that I'm using to compile my program. When I try and compile I get a long string of errors that look like this:
/tmp/cc70S4oH.o:Person.cpp:(.text+0x64): first defined here
/tmp/cctUpbgp.o: In function `Person::getName()':
stdDev.cpp:(.text+0xd0): multiple definition of `Person::getName()'
/tmp/cc70S4oH.o:Person.cpp:(.text+0xd0): first defined here
/tmp/cctUpbgp.o: In function `Person::getAge()':
stdDev.cpp:(.text+0xfe): multiple definition of `Person::getAge()'
/tmp/cc70S4oH.o:Person.cpp:(.text+0xfe): first defined here
/tmp/cchDhDS7.o: In function `Person::Person()':
main.cpp:(.text+0x0): multiple definition of `Person::Person()'
/tmp/cc70S4oH.o:Person.cpp:(.text+0x0): first defined here
/tmp/cchDhDS7.o: In function `Person::Person()':
main.cpp:(.text+0x0): multiple definition of `Person::Person()'
Here is my code with 4 files:
-------------------------------Person.hpp----------------------------
#ifndef MY_PERSON
# define MY_PERSON
#include<iostream>
using namespace std;
class Person
{
int age;
string name;
public:
// constructor
Person();
// constructor
Person(string, int);
// getter methods
string getName();
int getAge();
};
#endif
---------------------------------------------------Person.cpp--------------------------------------------------------------
#include "Person.hpp"
// constructor
Person::Person()
{
name = "";
age = 0;
}
// constructor
Person::Person(string n, int a)
{
name = n;
age = a;
}
// getter methods
string Person::getName()
{
return name;
}
int Person::getAge()
{
return age;
}
-------------------------------------------------stdDev.cpp-----------------------------------------------
#include "Person.cpp"
#include<cmath>
double stdDev(Person arr[], int n)
{
double mean = 0.0, sum = 0.0;
int i;
// get the total of age of all person
for( i = 0 ; i < n ; i++ )
{
sum += (double)arr[i].getAge();
}
// calculate mean
mean = sum / (double)n;
double temp_sum = 0.0;
for( i = 0 ; i < n ; i++ )
{
temp_sum += pow(arr[i].getAge() - mean, 2);
}
return sd;
}
-----------------------------------------------------main.cpp---------------------------------------------------------
#include "stdDev.cpp"
int main()
{
Person *arr = new Person[6];
I would advice putting all definitions in the .cpp and the declaring all the functions in the .hpp. With the extern keyword. It works for me, but I am looking for a better approach myself, for declaring and initializing classes in diff files.