Question

this a tiny simple program for my learning:

this is the declaring header:

#ifndef MATH_H
#define MATH_H

class Math
{
    private:
         int result;

    public:

        int addNumbers (int , int);
};

#endif // MATH_H

this is the class definition:

#include <iostream>
#include "Math.h"

using namespace std;

int Math::addNumbers(int a , int b)
{
    result = a + b ;
    cout<<result<<endl;

};

and this one is god damn Main ;)

#include <iostream>
#include "Math.h"

using namespace std;

int main()
{
    Math myMath;
    myMath.addNumbers(2,9);
};

and finally i got this error:

undefined reference to `Math::addNumbers(int, int)

i should tell you: the header file has the same name like my class name,

where is the problem?

best regards.

Amin khormaei

so the correct main should be like the below one:

#include <iostream>
#include "Math.h"
#include "MathDefinition.cpp"

using namespace std;

int main()
{
    Math myMath;
    myMath.addNumbers(2,9);
};
Was it helpful?

Solution

The problem is that the program you're trying to build is missing the definition for Math::addNumbers. This is probably due to the fact that you are only trying to build your main source file.
You need to make it so that the code defining Math::addNumbers ends up being linked into your program. To do that, you have two main options (let's assume that your files are called main.cpp and math.cpp):

  • You can modify your build system to also compile the math.cpp. This is generally regarded as the correct way to handle this situation. Unfortunately, the specifics depend on your build system or IDE...
    For instance, if you're using gcc, you could link both files into your binary using the following build command:

    gcc -o myprogram main.cpp math.cpp

  • You can simply #include "math.cpp" inside of main.cpp. This will lead to the code of math.cpp actually being part of main.cpp after preprocessing. This is generally not the recommended way of doing this, but is less environment-specific than the "proper" solution

OTHER TIPS

You might not be compiling your code correctly. Compile it with:

gcc main.cpp math.cpp -o math.o

Or shorter:

gcc *.cpp -o math.o

This will compile both math.cpp and main.cpp files

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top