系统相关
首页 > 系统相关> > Ubuntu 16.04安装gtest遇坑,成功安装及使用记录

Ubuntu 16.04安装gtest遇坑,成功安装及使用记录

作者:互联网

命令行安装失败

今天按照网上教程安装gtest

ubuntu@ubuntu:~$ sudo apt-get install libgtest-dev

安装完了之后写了一个测试案例test.cpp:

//test.cpp

# include <gtest/gtest.h>

int Add( int a, int b) //计算两数之和

{

	return a+b;

}

TEST(AddTest, IntTest)

{

	EXPECT_EQ( 8 , Add( 2 , 5 ));
	
	EXPECT_EQ( 7 , Add( 2 , 5 ));
	
	EXPECT_EQ( 6 , Add( 2 , 4 ));
	
	EXPECT_EQ( 15 , Add( 6 , 9 ));

}

int main( int argc, char **argv)

{

	testing::InitGoogleTest(&argc, argv);
	
	return RUN_ALL_TESTS();

}

终端输入

ubuntu@ubuntu:~$ g++ --std=c++11 test1.cpp -o test1 -lgtest_main -lgtest -lpthread

报错:
/usr/bin/ld: cannot find -lgtest

源码安装遇坑

github上下载源码:

ubuntu@ubuntu:~$ git clone https://github.com/google/googletest.git

源码编译:

ubuntu@ubuntu:~$ cd googletest
ubuntu@ubuntu:~/googletest$ mkdir build
ubuntu@ubuntu:~/googletest/build$ cd build
ubuntu@ubuntu:~/googletest/build$ cmake ..
ubuntu@ubuntu:~/googletest/build$ make -j

报错:
在这里插入图片描述
源码编译居然会报错。。。
仔细检查第一条错误,原来需要用c++11的标准来编译代码。
打开googletest文件夹里面的CMakeLists.txt
在里面新增这一行

add_definitions(-std=c++11) 

此时CMakeLists.txt为:

# Note: CMake support is community-based. The maintainers do not use CMake
# internally.

cmake_minimum_required(VERSION 2.8.12)
add_definitions(-std=c++11)    #########把这行加进去#################

if (POLICY CMP0048)
  cmake_policy(SET CMP0048 NEW)
endif (POLICY CMP0048)

project(googletest-distribution)
set(GOOGLETEST_VERSION 1.10.0)

if (CMAKE_VERSION VERSION_GREATER "3.0.2")
  if(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX)
    set(CMAKE_CXX_EXTENSIONS OFF)
  endif()
endif()

enable_testing()

include(CMakeDependentOption)
include(GNUInstallDirs)

#Note that googlemock target already builds googletest
option(BUILD_GMOCK "Builds the googlemock subproject" ON)
option(INSTALL_GTEST "Enable installation of googletest. (Projects embedding googletest may want to turn this OFF.)" ON)

if(BUILD_GMOCK)
  add_subdirectory( googlemock )
else()
  add_subdirectory( googletest )
endif()

修改完成之和,再进行编译。

ubuntu@ubuntu:~/googletest/build$ cmake ..
ubuntu@ubuntu:~/googletest/build$ make -j
ubuntu@ubuntu:~/googletest/build$ sudo make install

安装完成。

gtest测试

终端输入

ubuntu@ubuntu:~$ g++ --std=c++11 test.cpp -o test1 -lgtest_main -lgtest -lpthread

编译成功,在终端输入

ubuntu@ubuntu:~$  ./test

输出如下结果:
测试结果

标签:遇坑,16.04,c++,Add,googletest,build,ubuntu,安装,lgtest
来源: https://blog.csdn.net/qq_34525916/article/details/113752768