C ++ undefined reference to the class (1 header 2 cpp)

advertisements

I am reading a book (C++ for dummies) as well as watching youtube videos to learn how to code. I am currently struggling with very simple class functions.

Main.cpp

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
#include "Test.h"
using namespace std;

int x;

int main(int nNumberofArgs, char* pszArgs[])
{
    combat fight;
    cout << x;
    fight.dodmg();
    cout << x;
    return 0;
}

Test.h my header file with the class

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>

using namespace std;

#ifndef TEST_H_INCLUDED
#define TEST_H_INCLUDED
class combat
{
public:
    int dodmg();
    void zero_out();
private:
    int x;
};

#endif // TEST_H_INCLUDED

Test.cpp class functions

#include "Test.h"

int combat::dodmg()
{

    x = x - 5;
    return x;
}

void combat::zero_out()
{
    x = 20
}

I tried to make this very simplistic just to figure out how to work a class. I included a lot of #includes just to try and make sure it wasn't something stupid like I needed strings.

I am not sure why but the videos I watched simply had the header say ifndef TEST_H (of their respective code, mine has an _INCLUDE as well, I tried deleting it and it still didn't work.

My unfortunate errors

on line 14 of main.cpp fight.dodmg(); it says

\Beginning_Programming-CPP\Playing_with_class\main.cpp|14|undefined reference to `combat::dodmg()'|

then below that

||error: ld returned 1 exit status|


How are you compiling this? I think this is an issue because you arent compiling your Test.cpp file. If you arent already, try compiling with the command:

g++ main.cpp Test.cpp -o MyProgram

UPDATE:

Few things, you dont have a closing statement to your #ifndef directive in Text.h, you will need a constructor to set the value of x so i added one to the combat class also you were missing a semicolon in the zero_out function. I added comments to all the lines I changed.

Okay try this:

Test.h

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>

using namespace std;

#ifndef TEST_H_INCLUDED
#define TEST_H_INCLUDED
class combat
{
public:
   combat(); // added constructor
   int dodmg();
   void zero_out();
private:
   int x;
};

#endif // closed #ifndef

Text.cpp

#include "Test.h"

combat::combat() // implemented constructor
{
   x = 20;
}

int combat::dodmg()
{

   x = x - 5;
   return x;
}

void combat::zero_out()
{
   x = 20; // added ';'
}

Hope this helps,

Final edit: I dont think you really need your header guards in this scenario, you could remove the "#ifndef, #define, and the #endif" lines and not see a difference really