4

我刚刚将 google-test 源代码添加到libs/gtest-1.6.4我项目的目录中。有一个libs/gtest-1.6.4/CMakeLists.txt文件。在最上面CMakeLists.txt,我添加了add_subdirectory('libs/gtest-1.6.4'). 项目的结构是

|- CMakeLists.txt 
|- src 
   |- CMakeLists.txt 
   |- *.h and *.cc 
|- libs
   |- gtest-1.6.4
      |- CMakeLists.txt
      |- gtest source code etc.
|- other subdirectories 

现在我添加#include "gtest/gtest.h"一个头文件。编译失败

gtest/gtest.h: No such file or directory
compilation terminated.

这是我的src/CMakeLists.txt文件的片段。

set( Boost_USE_STATIC_LIBS ON )
find_package( Boost COMPONENTS graph regex system filesystem thread REQUIRED)

.. Normal cmake stuff ...
INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS} )

# This line is added for google-test
INCLUDE_DIRECTORIES(${GTEST_INCLUDE_DIRS} ${COMMON_INCLUDES})

add_executable(Partitioner
  print_function.cc
  methods.cc
  partitioner.cc
  main.cc
  )

TARGET_LINK_LIBRARIES(Partitioner ${Boost_LIBRARIES})
TARGET_LINK_LIBRARIES(Partitioner ${GTEST_LIBRARIES})

我错过了什么?

4

2 回答 2

7

查看GTest 的 CMakeLists.txt,看起来它们的包含路径是${gtest_SOURCE_DIR}/include. 他们还将库定义为一个名为的 CMake 目标(这包含在当前第 70 行gtest的宏中)。cxx_library(gtest ...)

所以看起来你需要这样做:

...
# This line is added for google-test
INCLUDE_DIRECTORIES(${GTEST_INCLUDE_DIRS} ${COMMON_INCLUDES})
INCLUDE_DIRECTORIES(${gtest_SOURCE_DIR}/include ${COMMON_INCLUDES})
...
TARGET_LINK_LIBRARIES(Partitioner ${Boost_LIBRARIES})
TARGET_LINK_LIBRARIES(Partitioner ${GTEST_LIBRARIES})
TARGET_LINK_LIBRARIES(Partitioner ${Boost_LIBRARIES} gtest)

您还必须确保在您的根 CMakeLists.txt 中,您之前调用add_subdirectory(libs/gtest-1.6.4) 过, add_subdirectory(src)以便在“src/CMakeLists.txt”中使用 GTest 变量时正确设置它们。

于 2013-08-04T20:41:25.953 回答
0

接受的答案中所述,

我确实把我的GoogleTest东西放在我的add_subdirectory()台词之前,它起作用了。

# The ROOT CMakeLists.txt

enable_testing()

include(CTest)

# https://google.github.io/googletest/quickstart-cmake.html
include(FetchContent)
FetchContent_Declare(
        googletest
        URL https://github.com/google/googletest/archive/....zip
)
# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)
include(GoogleTest)


add_subdirectory(some)
add_subdirectory(other)
add_subdirectory(another)

在其中一个子目录中,我看到测试工作。

# A CMakeLists.txt in a sub directory

#enable_testing()    # NOT REQUIRED, hence, commented out
#include(CTest)      # NOT REQUIRED, hence, commented out
#include(GoogleTest) # NOT REQUIRED, hence, commented out

add_executable(
        mytest
        test/mytest.cpp
)
target_link_libraries(
        mytest
        gtest_main
)

gtest_discover_tests(
        mytest
)
于 2021-09-24T13:27:02.273 回答