1. 编译
1.1 步骤
- 下载源码并解压: https://github.com/google/googletest
- 新建build文件夹和install文件夹
- 使用cmake-gui来生成vs工程
- 在cmake-gui中设置源文件和编译文件夹路径,如下图所示
- configure,设置好install路径,勾选gtest_force_shared_crt
- configure
- generate
- Open Project
- 生成 INSTALL target (release和debug库切换生成)
1.2 注意事项
windows下如果不勾选"gtest_force_shared_crt"编译选项,则是生成链接MT运行时库的库,使用的时候需要设置使用程序为链接MT运行时库。
链接MD运行时库,则要勾选"gtest_force_shared_crt"编译选项
2. 使用
文件树
.
├── CMakeLists.txt
└── src
└── main.cpp
2.1 CMakeLists.txt
cmake_minimum_required(VERSION 3.5.1)
project(cmake_gtest)
# ------------------------------------------------------------------
# gtest
# ------------------------------------------------------------------
set(GTEST "D:/deptrum/22_code/91_open_source/googletest_install/")
include_directories("${GTEST}/include")
link_directories("${GTEST}/lib")
# ------------------------------------------------------------------
# source files
# ------------------------------------------------------------------
include_directories("${CMAKE_SOURCE_DIR}/src")
AUX_SOURCE_DIRECTORY("${CMAKE_SOURCE_DIR}/src" PROJECT_SRCS)
FILE(GLOB PROJECT_HDRS ${CMAKE_SOURCE_DIR}/src/*.h ${CMAKE_SOURCE_DIR}/src/*.hpp)
# ------------------------------------------------------------------
# ${PROJECT_NAME}
# ------------------------------------------------------------------
add_executable(${PROJECT_NAME} ${PROJECT_SRCS} ${PROJECT_HDRS})
target_link_libraries(${PROJECT_NAME} debug gtestd.lib)
target_link_libraries(${PROJECT_NAME} optimized gtest.lib)
2.2 main.cpp
#include <gtest/gtest.h>
int Foo(int a, int b)
{
if (a == 0 || b == 0)
{
throw "don't do that";
}
int c = a % b;
if (c == 0)
return b;
return Foo(b, c);
}
TEST(FooTest, HandleNoneZeroInput)
{
EXPECT_EQ(2, Foo(4, 10));
EXPECT_EQ(6, Foo(30, 18));
}
int main(int argc, char* argv[])
{
testing::InitGoogleTest(&argc, argv);
RUN_ALL_TESTS();
getchar();
return 0;
}
使用cmake生成vs工程后,便可运行上述例子
3. 扩展
也可使用源码形式把googletest引入到使用工程中,参考下面的链接:
https://github.com/google/googletest/blob/master/googletest/README.md#incorporating-into-an-existing-cmake-project
网友评论