c++ - .CPP中的类定义时,CMake for Google测试

标签 c++ unit-testing class cmake googletest

当我的类定义位于.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/

例。导师
#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

讲师
#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;
}

最佳答案

如果要获取这种“ undefined reference ”,请确保链接编译Instructor.cpp的结果,或者Instructor.cpp是测试的依赖项,具体取决于构建的组织方式。

这可能很简单:

add_executable(runTests tests.cpp Instructor.cpp)

虽然这可能需要根据您的路径的具体情况进行调整。

关于c++ - .CPP中的类定义时,CMake for Google测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60645475/

相关文章:

unit-testing - 初学者单元测试 - 测试方法的复杂输入

c++ - 使用新位图修改 CreateToolbarEx 函数时出现内存分配问题

c++ - 使用可变参数模板实现 Get(Tuple) 得到 "parameter packs not expanded with ‘...’“错误

c# - 什么是等同于在 Rhino Mocks 中使用 Ordered() 的 AAA 语法

unit-testing - 我可以仅使用浅层渲染而不安装完整的组件树来完成所有单元测试吗?

java - Matlab 类的 Tab 补全

python - 在 Python 中,如果给出错误的参数,则返回 “None” 而不是创建新实例

c++ - 如何使用派生类从基类设置字符串数据成员?

c++ - nullptr 可以用作变量参数(varargs)吗?

c++ - 在调用 future.get() 之前销毁 std::promise 是否可以?