When my class definitions are inside my .h files, my make command did not give any errors and my tests were passing successfully.
However, as soon as I move the class definitions to .cpp files, I get an undefined reference to `Class::method(int)'
for everything. How should I change my CMakeLists.txt accordingly?
CMakeLists.txt
cmake_minimum_required(VERSION 2.6)
# Locate GTest
find_package(GTest REQUIRED)
include_directories(${GTEST_INCLUDE_DIRS})
# Link runTests with what we want to test and the GTest and pthread library
add_executable(runTests tests.cpp)
target_link_libraries(runTests ${GTEST_LIBRARIES} ${GTEST_MAIN_LIBRARIES} pthread)
I have followed this tutorial:
https://www.eriksmistad.no/getting-started-with-google-test-on-ubuntu/
Example. Instructor.h
#ifndef INSTRUCTOR_H
#define INSTRUCTOR_H
#include <iostream>
#include <vector>
using namespace std;
class Instructor
{
int instrId;
string instrEmail;
string instrPassword;
public:
Instructor();
void showGameStatus();
void setInstrId(int newInstrId);
int getInstrId();
};
#endif
Instructor.cpp
#include <iostream>
#include "Instructor.h"
using namespace std;
Instructor::Instructor()
{
cout << " Default Instructor Constructor\n";
instrId = 0;
instrEmail = "@jaocbs-university.de";
instrPassword = "123";
}
void Instructor::setInstrId(const int newInstrId)
{
instrId = newInstrId;
}
int Instructor::getInstrId()
{
return instrId;
}
If you're getting "undefined reference" of that sort make sure you're linking in the result of compiling Instructor.cpp
, or that Instructor.cpp
is a dependency of the test depending on how your build is organized.
This may be as simple as:
add_executable(runTests tests.cpp Instructor.cpp)
Though that may need to be adjusted based on the specifics of your path.