0

Just had a little problem that I haven't been able to figure out yet. I was using a similar program structure for a different project, but the problem boils down to this. I have two cpp files, which are:

Trading_dte.cpp :

#include <iostream>
using namespace std;
class Dte
{
    public:
    int addition(int a, int b)
    {
        return a + b;
    }
};

dummy.cpp :

#include <iostream>
#include "Trading_dte.hpp"

Dte obj;

int check()
{
    std::cout<<obj.addition(6,9);
}

I created a header file called Trading_dte.hpp :

# pragma once
#include <iostream>

class Dte
{
    public:
    int addition(int a, int b);
}; 

Now when I try compiling using the command :

g++ Trading_dte.cpp dummy.cpp

I get the error :

/usr/bin/ld: /tmp/ccCcM8R6.o: in function `check':
dummy.cpp:(.text+0x1a): undefined reference to `Dte::addition(int, int)'
collect2: error: ld returned 1 exit status

I'm sure it's something small, but I just can't figure what. Thanks a lot in advance!

2 Answers2

4

your cpp file need to be written differently

#include "Trading_dte.hpp"
#include <iostream>

int Dte::addition(int a, int b)
{
  return a + b;
}
AndersK
  • 35,813
  • 6
  • 60
  • 86
  • I'm struggling to find a good SO answer/blog post/whatever explaining WHY this is the right thing to do. – orhtej2 Nov 17 '21 at 18:10
  • @orhtej2 the class declaration is in the header, the implementation in the .cpp or alternatively you can put everything in the header. – AndersK Nov 18 '21 at 12:39
3

You've created two separate Dte classes, one visible to main and another visible only in Trading_dte.cpp. The one visible to main, defined in Trading_dte.hpp has a declaration of the addition member function but no definition.

Probably the easiest thing to do is to drop Trading_dte.cpp and put the implementation into the class definition in Trading_dte.hpp.

Trading_dte.hpp:

# pragma once

class Dte
{
    public:
    int addition(int a, int b)
    {
        return a + b;
    }
};

Note that I also removed the #include <iostream> line. You don't need it in the header file because you don't use it in the class.

jkb
  • 2,376
  • 1
  • 9
  • 12