当我的类定义位于.h文件中时,我的make命令未给出任何错误,并且我的测试已成功通过。
但是,一旦我将类定义移动到.cpp文件,我将得到所有内容的undefined reference to `Class::method(int)'
。我应该如何相应地更改CMakeLists.txt?
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)
我已遵循本教程:
https://www.eriksmistad.no/getting-started-with-google-test-on-ubuntu/
示例。 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;
}
如果获得这种“未定义的引用”,请确保链接的是编译Instructor.cpp
的结果,或者Instructor.cpp
是测试的依赖项,具体取决于构建的组织方式。
这可能很简单:
add_executable(runTests tests.cpp Instructor.cpp)
尽管可能需要根据路径的具体情况进行调整。