Home > Enterprise >  Why am I getting an undefined reference error while using separate .cpp and .h files for a class?
Why am I getting an undefined reference error while using separate .cpp and .h files for a class?

Time:02-22

I am using a simple function to add to integers, the class is declared in the Adder.h file as below

class Adder
{
    public:
    int add (int x, int y);
};

Then I have the Adder.cpp file which has the function definition

int add (int x, int y)
{
    return x   y;
}

Then the main.cpp file which calls the function

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

using namespace std;

int main()
{
    Adder adder1;
    int result = adder1.add (2, 3);
    cout << result;
}

I ran g -c Adder.cpp to create Adder.o file beforehand. Then I ran g main.cpp but go the following error

main.cpp:(.text 0x2d): undefined reference to `Adder::add(int, int)'

Where am I going wrong?

CodePudding user response:

In your second and final step, you didn't instruct the compiler (linker more exactly) to take into account Adder.o, so your final executable still doesn't know the implementation of Adder::add Try, after getting Adder.o, to run g main.cpp Adder.o

Also, this may be relevant : Difference between compiling with object and source files

Also, if that is the complete code, as others have pointed out, in the Adder.cpp, you are just defining a simple function, not the one from the Adder class.

CodePudding user response:

The problem is that you've defined a free function named add instead of defining a member function of class Adder. To define add as a member function we have to be in the scope of the class Adder which we can do by adding Adder:: before add as shown below:

Adder.cpp

//note the use of scope resolution operator ::
int Adder::add(int x, int y)//define a member function instead of a free function
{
    return x   y;
}

In the above modified code, we are defining the member function add instead of the free function add.

  •  Tags:  
  • c
  • Related