-3

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?

273K
  • 19,191
  • 8
  • 34
  • 47
  • 4
    Does this answer your question? [How to use Libraries](https://stackoverflow.com/questions/10358745/how-to-use-libraries) – Maaz Feb 21 '22 at 15:35
  • You haven't passed in "Adder.o" when compiling the program with "main.cpp". – cigien Feb 21 '22 at 15:37
  • 1
    You define a free function in .cpp, You do not implement the class method. – 273K Feb 21 '22 at 15:39
  • 1
    @Maaz Although the other answers were much more concise but the link you shared was very informative. Thanks a lot :) – Paawan Angra Feb 22 '22 at 16:53

2 Answers2

1

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.

1

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.

Anoop Rana
  • 19,715
  • 4
  • 12
  • 33