Question

I am learning C++ and CppUnit at the same time, using netbeans 7.2.

I create the following file

#include <cstdlib>

using namespace std;

/*
 * 
 */
class Subtract{
public:
    int minus(int a, int b){
        return a-b;
    }
};

int main(int argc, char** argv) {

    return 0;
}

And then I right-click to generate the following cppunit test file

#include "newtestclass.h"


CPPUNIT_TEST_SUITE_REGISTRATION(newtestclass);

newtestclass::newtestclass() {
}

newtestclass::~newtestclass() {
}

void newtestclass::setUp() {
}

void newtestclass::tearDown() {
}

int Subtract::minus(int a, int b);

void newtestclass::testMinus() {
    int a=89;
    int b=55;
    Subtract subtract;
    int result = subtract.minus(a, b);
    CPPUNIT_ASSERT_EQUAL(34,result);
}

When I try to run the test, it gives the following errors

g++    -c -g -I. -MMD -MP -MF build/Debug/GNU-MacOSX/tests/tests/newtestclass.o.d -o build/Debug/GNU-MacOSX/tests/tests/newtestclass.o tests/newtestclass.cpp
tests/newtestclass.cpp:25: error: 'Subtract' has not been declared
tests/newtestclass.cpp: In member function 'void newtestclass::testMinus()':
tests/newtestclass.cpp:30: error: 'Subtract' was not declared in this scope
tests/newtestclass.cpp:30: error: expected `;' before 'subtract'
tests/newtestclass.cpp:31: error: 'subtract' was not declared in this scope
make[1]: *** [build/Debug/GNU-MacOSX/tests/tests/newtestclass.o] Error 1
make: *** [.build-tests-impl] Error 2

How do I get this to work properly?

Was it helpful?

Solution

In C++, the convention is to declare the classes and functions in a header file (.h file) and implement them in the source file (.cpp file).

Your Subtract.h file (declarations) should have only this:

class Subtract {
public:
    int minus(int a, int b);
};

Your Subtract.cpp file (implementation) should have this:

#include "Subtract.h"

int Subtract::minus(int a, int b)
{
    return a-b;
}

Then you #include "Subtract.h" in your newtestclass.cpp file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top