1
votes

I have a simple CMake + Qt + GTest project:

.
├── 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)

And I want to reach calculator.h in calculator_test.cpp which uses GTest:

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

I have tried to link but then test is not found and the path is releative:

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
)

How to link calculator.h in calculator_test.cpp test with CMakeLists.txt?

1
You confuse terms: by "linking" we mean the binding of the object files (compiler output) with each other to produce the resulting binary executable. I can only assume that in your case the compiler cannot find "calculator.h" while compiling "calculator_test.cpp" which is fixable by providing include path. The problem is with compiler environment set up in project file then.Alexander V

1 Answers

1
votes

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

You can specify the include path:

include_directories("${PROJECT_SOURCE_DIR}/relativePathToHeader")

and likely the path needed:

include_directories("${PROJECT_SOURCE_DIR}/src/utils") or maybe include_directories("${PROJECT_SOURCE_DIR}/utils") depending on where the source directory actually is.

You need to re-run CMake, of course.