gtest:对'operator +'

时间:2017-11-26 15:15:15

标签: googletest

这只是一个观察,但我不明白问题出在哪里。我实现了向量加法运算符,一切都在main函数中运行得很好。但是当我尝试通过Google Test测试时,我收到了编译错误

In function `ZN15Basic_Dirs_Test8TestBodyEv':
C:/Users/home/Documents/clion/example/test/main.cpp:10: undefined reference
to `operator+(std::vector<int, std::allocator<int> > const&, 
std::vector<int, std::allocator<int> > const&)'

但是,当我删除src / class.cpp文件时,它会编译。你能告诉我它是如何工作的吗? :)

代码如下。

的src / class.h

 #ifndef EXAMPLE_CLASS_H
 #define EXAMPLE_CLASS_H

 #include <vector>

 std::vector<int> operator+(const std::vector<int>& a, const std::vector<int>& b);

 #endif //EXAMPLE_CLASS_H

的src / class.cpp

#include "class.h"

std::vector<int> operator+(const std::vector<int>& a, const std::vector<int>& b) {
     if (a.size() != b.size()) {
         std::cerr << "vectors are not of the same size!\n";
         exit(1);
     }
     std::vector<int> res(a.size());
     for (unsigned i = 0; i < a.size(); ++i) {
         res[i] = a[i] + b[i];
     }
     return res;
}

测试/ main.cpp中

#include "class.h"
#include <gtest/gtest.h>

using namespace std;

TEST(Basic, Dirs) {
    std::vector<int> a = {1, 1, 0};
    std::vector<int> b = {2, 1, 0};
    std::vector<int> c = a+b;
    EXPECT_EQ(c[0], 3);
    EXPECT_EQ(c[1], 2);
    EXPECT_EQ(c[2], 0);
}

./ CMakeLists

cmake_minimum_required(VERSION 3.7)
project(example)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES src/main.cpp src/class.cpp)
add_subdirectory(test)
add_executable(example ${SOURCE_FILES})

测试/ CMakeLists

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall")
add_subdirectory("../lib/googletest" "${CMAKE_CURRENT_BINARY_DIR}/gtest_build")
include_directories(../lib/googletest/googletest/include)
include_directories(../src/)
add_executable(runtest main.cpp)
target_link_libraries(runtest gtest gtest_main)

1 个答案:

答案 0 :(得分:0)

您忘记将runtest gtest可执行文件与example

相关联

./ CMakeLists

cmake_minimum_required(VERSION 3.7)
project(example)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES src/main.cpp src/class.cpp)
add_executable(example ${SOURCE_FILES})
add_subdirectory(test)

测试/ CMakeLists

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall")
add_subdirectory("../lib/googletest" "${CMAKE_CURRENT_BINARY_DIR}/gtest_build")
include_directories(../lib/googletest/googletest/include)
include_directories(../src/)
add_executable(runtest main.cpp)
target_link_libraries(runtest gtest gtest_main example)

同样不是将example实际定义为共享库而不是可执行文件(只需删除main函数 - 您可能根本不需要它)可能更好:< / p>

add_library(example SHARED ${SOURCE_FILES})