连接

时间:2018-04-21 16:45:02

标签: c++ qt cmake qt5 googletest

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

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

Root 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));
}

我试图链接但是找不到测试并且路径是相关的:

测试/ 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
)

如何使用 calculator_test.cpp 测试 calculator_test.cpp 测试中的 calculator.h

1 个答案:

答案 0 :(得分:1)

  

我的Qt项目与CMake项目文件无法解析路径   “someHeader.h”。我该怎么做才能解决它?

您可以指定包含路径:

include_directories("${PROJECT_SOURCE_DIR}/relativePathToHeader")

可能需要的路径:

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

当然,你需要重新运行CMake。