C++ 当类定义位于.CPP中时,用于Google测试的CMake

C++ 当类定义位于.CPP中时,用于Google测试的CMake,c++,unit-testing,class,cmake,googletest,C++,Unit Testing,Class,Cmake,Googletest,当我的类定义在.h文件中时,make命令没有给出任何错误,并且我的测试成功通过 但是,一旦我将类定义移动到.cpp文件,我就会得到一个对`class::method(int)的未定义引用。我应该如何相应地更改CMakeLists.txt CMakeLists.txt cmake_minimum_required(VERSION 2.6) # Locate GTest find_package(GTest REQUIRED) include_directories(${GTEST_INCLUDE

当我的类定义在.h文件中时,make命令没有给出任何错误,并且我的测试成功通过

但是,一旦我将类定义移动到.cpp文件,我就会得到一个
对`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)
我遵循了本教程:

例如。讲师

#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
\ifndef讲师
#定义讲师
#包括
#包括
使用名称空间std;
班主任
{
int instrId;
弦乐;
字符串instrPassword;
公众:
讲师();
void showGameStatus();
void setInstrId(int newInstrId);
int getInstrId();
};
#恩迪夫
讲师.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;
}
#包括
#包括“讲师.h”
使用名称空间std;
讲师::讲师()
{
cout如果您得到的是这种类型的“未定义引用”,请确保您链接的是编译
讲师.cpp
的结果,或者
讲师.cpp
是测试的依赖项,具体取决于构建的组织方式

这可能很简单:

add_executable(runTests tests.cpp Instructor.cpp)

尽管这可能需要根据路径的具体情况进行调整。

为什么要将它们移动到
.cpp
文件中,而不是将它们保存在头文件中,以便测试更容易访问它们?如果需要测试代码,则需要在
.cpp
文件之外访问它,这意味着您需要一个头文件。难道不建议将类定义和声明放在单独的文件中吗?至少这是我在学校学到的。我用一个例子编辑了qs,说明了我的意思,以防不清楚@Tadman。你的例子现在让事情变得更清楚了。我把“定义”误解为“声明”,把“定义”误解为“实现”。