与柯南一起安装的GTest:未定义的引用

时间:2017-02-10 14:40:28

标签: c++ cmake googletest conan

我尝试使用通过conan安装的gtest,但最终导致未定义的引用链接器错误。这个问题或多或少是this stackoverflow question的后续问题。但我认为提供的例子很简单。我使用gcc 6.3在最新的arch linux x64下编译。

可能存在一些C ++版本的错配吗?或者您对如何解决问题有任何其他想法?

我将在下面提供我的源代码:

目录树:

tree
.
├── CMakeLists.txt
├── conanfile.txt
└── main.cpp

main.cpp中:

#include <iostream>
#include <gtest/gtest.h>

class TestFixture : public ::testing::Test {
protected:
    void SetUp(){
    std::cout << "SetUp()" << std::endl;
    }

    void TearDown(){
    std::cout << "TearDown()" << std::endl;
    }
};



TEST_F (TestFixture, shouldCompile) {
    std::cout << "shouldCompile" << std::endl;
    ASSERT_TRUE(true); // works, maybe optimized out?
    ASSERT_TRUE("hi" == "hallo"); // undefined reference

}

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

CMakeLists.txt:

project(ConanGtestExample)
cmake_minimum_required(VERSION 2.8.12)

set(CMAKE_CXX_STANDARD 11)

include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
conan_basic_setup()

# Necessary to compile gtest
# - dependencies and final build
#   need to be compiled with same
#   build type. Otherwise linker
#   error will occure.
set(CMAKE_BUILD_TYPE Release)

add_executable(main main.cpp)
target_link_libraries(main ${CONAN_LIBS})

conanfile.txt:

[requires]
gtest/1.7.0@lasote/stable

[generators]
cmake

我尝试使用以下命令构建项目:

mkdir build
cd build
conan install -s build_type=Release .. --build=missing
cmake .. -DCMAKE_BUILD_TYPE=Release 
cmake --build .

未定义的参考输出:

Scanning dependencies of target main
[ 50%] Building CXX object CMakeFiles/main.dir/main.cpp.o
[100%] Linking CXX executable bin/main
CMakeFiles/main.dir/main.cpp.o: In function `TestFixture_shouldCompile_Test::TestBody()':
main.cpp:(.text+0x99): undefined reference to `testing::internal::GetBoolAssertionFailureMessage[abi:cxx11](testing::AssertionResult const&, char const*, char const*, char const*)'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/main.dir/build.make:95: bin/main] Error 1
make[1]: *** [CMakeFiles/Makefile2:68: CMakeFiles/main.dir/all] Error 2
make: *** [Makefile:84: all] Error 2

2 个答案:

答案 0 :(得分:4)

我找到了一个问题的答案:

问题是conan会下载/编译gtest二进制文件 默认情况下,即使我的编译器(gcc 6.3)使用libstdc++ 默认情况下为libstdc++11。因此libstdc++之间存在不匹配libstdc++11

要解决此问题,您必须明确告诉conan使用libstdc ++ 11进行编译:

conan install .. --build missing -s compiler=gcc -s compiler.version=6.3 -s compiler.libcxx=libstdc++11

答案 1 :(得分:1)

我最终不得不在项目的self.options['gtest'].shared = True中添加conanfile.py来解决这个问题。以前,由于某些与Windows无关的原因,它被设置为false。

尝试更改为gtest / gmock的共享库,如果像我一样,您看到默认设置已经libstdc++11,那么更改conan install args是不够的。