in main.cpp if i include the header files, it raises the error
1 2 3 4 5 6 7
metulburr@ubuntu:~/Documents/cplusplus/composition$ g++ main.cpp -o main
/tmp/ccb7S83C.o: In function `main':
main.cpp:(.text+0x20): undefined reference to `Birthday::Birthday(int, int, int)'
main.cpp:(.text+0x58): undefined reference to `People::People(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, Birthday)'
main.cpp:(.text+0x7c): undefined reference to `People::printinfo()'
collect2: ld returned 1 exit status
metulburr@ubuntu:~/Documents/cplusplus/composition$
files in same directory:
1 2 3
metulburr@ubuntu:~/Documents/cplusplus/composition$ ls
Birthday.cpp Birthday.h main.cpp People.cpp People.h
metulburr@ubuntu:~/Documents/cplusplus/composition$
but if i include the cpp files, it compiles and works. On the other hand, as i googled around for the reason the only thing i could find was to never include a cpp file as it compiles twice. So what would cause the header files to cause compiles errors and not cpp files? And what might i do to fix it?
main.cpp
1 2 3 4 5 6 7 8 9 10
#include <iostream>
#include "Birthday.h"
#include "People.h"
usingnamespace std;
int main(){
Birthday birthobj(2,27,1987);
People pers1("Micah Robert", birthobj);
pers1.printinfo();
}
#ifndef BIRTHDAY_H
#define BIRTHDAY_H
class Birthday{
public:
Birthday(int m, int d, int y);
void printdate();
private:
int month;
int day;
int year;
};
#endif
Birthday.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include "Birthday.h"
#include <iostream>
usingnamespace std;
Birthday::Birthday(int m, int d, int y){
month = m;
day = d;
year = y;
}
void Birthday::printdate(){
cout << month << "/" << day << "/" << year << endl;
}
People.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#ifndef PEOPLE_H
#define PEOPLE_H
#include <string>
#include "Birthday.h"
usingnamespace std;
class People{
public:
People(string x, Birthday y);
void printinfo();
private:
string name;
Birthday dateofbirth; //pass in obj to People class
};
#endif
People.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include "People.h"
#include "Birthday.h"
#include <iostream>
usingnamespace std;
People::People(string x, Birthday y)
: name(x), dateofbirth(y)
{
}
void People::printinfo(){
cout << name << "was born on ";
dateofbirth.printdate();
}