CMake + Qt + GTest 文件链接

CMake + Qt + GTest files linking

我有一个简单的 CMake + Qt + GTest 项目:

.
├── CMakeLists.txt
├── src
│   ├── CMakeLists.txt
│   ├── main.cpp
│   └── utils
│       ├── calculator.cpp
│       └── calculator.h
└── tests
    ├── calculator_test.cpp
    └── CMakeLists.txt

根目录CMakeFiles.txt

cmake_minimum_required(VERSION 3.5)

project(random_project)

# Place binaries and libraries according to GNU standards.
include(GNUInstallDirs)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR})
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR})
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_BINDIR})

# Add source folder.
add_subdirectory(src)

# Add GTest.
include(cmake/googletest.cmake)
fetch_googletest(
        ${PROJECT_SOURCE_DIR}/cmake
        ${PROJECT_BINARY_DIR}/googletest
)

enable_testing()

# Add tests folder.
add_subdirectory(tests)

我想在使用 GTest 的 calculator_test.cpp 中达到 calculator.h:

#include <gtest/gtest.h>
#include "utils/calculator.h" // <- Want to reach this in that path format.

TEST(example, add)
{
    EXPECT_EQ(8, Calculator::sum(3, 5));
}

我试过 link 但后来找不到测试,路径是相关的:

tests/CMakeFiles.txt

# Find the Qt libraries.
find_package(Qt5Widgets REQUIRED)

# Qt5 libraries.
set(QT5_LIBRARIES
        Qt5::Widgets)

# Source files.
set(SOURCE_FILES
        calculator_test.cpp
        ../src/utils/calculator.cpp
        ../src/utils/calculator.h
        ../src/main.cpp) # If I link like this, test is not found.

# Tell CMake to create the executable.
add_executable(unit_tests ${SOURCE_FILES})

# Use the Widgets module from Qt5.
target_link_libraries(unit_tests ${QT5_LIBRARIES} gtest_main)

# Add tests.
add_test(
        NAME unit_tests
        COMMAND ${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}/unit_tests
)

如何 link calculator.hcalculator_test.cpp 中使用 进行测试CMakeLists.txt?

My Qt project with CMake project file cannot resolve the path to "someHeader.h". What can I do to fix it?

您可以指定包含路径:

include_directories("${PROJECT_SOURCE_DIR}/relativePathToHeader")

可能需要的路径:

include_directories("${PROJECT_SOURCE_DIR}/src/utils") 或者也许 include_directories("${PROJECT_SOURCE_DIR}/utils") 取决于源目录的实际位置。

当然需要重新运行CMake。