Search code examples
c++oopundefined

Why do I get an Undefined reference error when trying to compile?


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!


Solution

  • your cpp file need to be written differently

    #include "Trading_dte.hpp"
    #include <iostream>
    
    int Dte::addition(int a, int b)
    {
      return a + b;
    }