Situation is as follows: I've got a simple project consisting of two files - Calc.h
and Calc.cpp
.
Calc.h:
#pragma once
class Calc {
public:
int add(int,int);
static const int a = 42;
}
Calc.cpp:
#include "Calc.h"
class Calc {
public:
int add(int a,int b){
return a b;
};
}
CalcTestSuite.h:
#pragma once
#include "Calc.h"
#include <cxxtest/TestSuite.h>
class CalcTestSuite : public CxxTest::TestSuite {
public:
void testAddition(void)
{
Calc calculator;
TS_ASSERT_EQUALS(calculator.a, 42);
TS_ASSERT_EQUALS(calculator.add(1,2), 3);
}
}
The problem
The problem being is, when I do cxxtestgen --error-printer -o runner.cpp CalcTestSuite.h && g -I$cxxtest -o runner.o runner.cpp && ./runner.o
, an error occurs:
runner.cpp: (.text._ZN13...(many letters)): undefined reference to `Calc::add(int,int)`
Undoubtedly, the reason of that is wrong compiling as I compile code outside of Visual Studio 2019 or other IDE.
How I tried to solve the problem:
I see a couple of solutions:
1.) Leave build command as is and add #include "Calc.cpp"
to TestSuite file, which will obviously work but would be a bad practice.
2.) Add Calc.cpp to g command: g -I$cxxtest -o runner.o Calc.cpp runner.cpp && ./runner.o
, however, it leads to another problem:
Calc.cpp:3:7: error: redefinition of 'class Calc'
In that case I also tried changing #pragma once
to #ifndef CALC_H...
block in Calc.h
, but the error remained.
I tried searching for real-world cxxtest code examples, but didn't find the site I've seen long ago. I would be glad to recieve any tips on what's the best way to deal with this issue.
And if you know the site where I can search for real-life code snippets I would be glad if you shared it.
CodePudding user response:
There are two problems:
You are violating One Definition Rule! You can't redefine Calc
like this:
#include "Calc.h"
class Calc {
public:
int add(int a,int b){
return a b;
};
}
It must be:
#include "Calc.h"
int Calc::add(int a,int b) {
return a b;
};
const int Calc::a;
Now this problem do not surfaces since you do not build this cpp and you should.
You didn't explain how you are building you code. Simplest way when it is done manually it can look like this:
cxxtestgen --error-printer -o CalcTestSuite.cpp CalcTestSuite.h
g -std=c 17 -Wall -Wextra Calc.cpp CalcTestSuite.cpp -o test
Offtopic: this cxxtest
test framework is strange and has strange/complex build process of test. It would be better if you learn to use something more useful, Catch2
is great and easy to use (no funny build process) and it is supported by godbolt.