Undefined reference to Class

I have a header and 2 source files. I want to link the functions from Car.cpp to the header file Car.h, but when i run the MainFile.cpp there seems to be the Error : Undefined reference to 'Car::<functions>'. I followed the video from: https://www.youtube.com/watch?v=O2VlTRZY3yc&index=1&list=PL0E9BC89BD7E5CA43 .

Here's the whole code :
MainFile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
#include "Car.h"
using namespace std;


int main()
{
    Car Betsy;
    Betsy.setNumOfHeadlights(2);
    cout << Betsy.getNumOfHeadlights();
    cout<<endl;
    Betsy.setHeadlightStatus(true);
    cout << Betsy.getHeadlightStatus();

    return 0;
}


Car.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

#ifndef CAR_H
#define CAR_H


class Car
{
private:
        int numOfHeadlights;
        bool headlightStatus;
public:
        void setNumOfHeadlights(int numIn);
        int getNumOfHeadlights();
        void setHeadlightStatus(bool statusIn);
        bool getHeadlightStatus();
};

#endif 


Car.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include "Car.h"


void Car::setNumOfHeadlights(int numIn)
{
    numOfHeadlights = numIn;
}

int Car::getNumOfHeadlights()
{
    return numOfHeadlights;
}

void Car::setHeadlightStatus(bool statusIn)
{
    headlightStatus = statusIn;
}

bool Car::getHeadlightStatus()
{
    return headlightStatus;
}
Last edited on
What program are you using to compile?

If you are using the command line, you need to include car.cpp in your rule:
$ g++ Main.cpp Car.cpp -o my_program

If you are using an IDE, you made some mistake and car.cpp is not actually in the project.

Btw, Car.h ( and Car.cpp ) don't need iostream. You should take line 1-3 out of Car.h. If, at some point Car.cpp does require isosteam, you should put the include in Car.cpp
I am using Code Blocks.
With CB you have to make an empty project to make it. Otherwise you are stuck doing command line compilation instead of using the IDE.
BHX
Can you please explain this in detail. I really don't know what you're talking about.
Thanks BHX it worked! Just a quick question. Why didn't you include the iostream and the namespace std in the Car.h file?
As pointed out by Lowest0ne, at this time you aren't using anything from iostream or the standard namespace in Car.h or Car.cpp so there is no need to even have them in it. You should only include headers in files where they are actually used. While I use the global namespace in examples to save typing, I recommend never using it outside of the file that has your main function in it.
Topic archived. No new replies allowed.