Search code examples
c++cmakectest

CMake: can't find header files


I have a directory main, which has the following subdirectories: A, B, C, D, Test.

In Test, I have a CMakeLists file with the following content:

cmake_minimum_required(VERSION 2.8)
enable_testing()
set(TEST_EXE_NAME test)
add_executable(${TEST_EXE_NAME} test.cpp)
add_test(NAME "testDatabase" COMMAND ${TEST_EXE_NAME})
target_include_directories(Test PUBLIC ./)
target_include_directories(Test A B C D)
target_link_libraries(Test A B C D)

In Test, I have an executable which #includes several header files from A, B, C, and D.

However, after doing make, I get the message that cmake cannot find these header files from A, B, C, and D.

How can I make this go away?


Solution

  • From your question, it is hard to see exactly what is going wrong. This is why I am going to describe how I would tackle the whole problem.

    In your "directory main"

    It is necessary to have a CMakeLists.txt here to be able to use the CMake targets for A-D in Test. It would look like this:

    cmake_minimum_required(VERSION 2.8)
    enable_testing()
    add_subdirectory(A)
    add_subdirectory(B)
    add_subdirectory(C)
    add_subdirectory(D)
    add_subdirectory(Test)
    

    Note that we call enable_testing() here. This will enable you to call make test in your root build directory directly later on.

    In the folders A-D

    There, you create libraries for A-D. For A, for instance, you would write:

    add_library(A STATIC [... source files for A ...]) # or SHARED instead of STATIC
    target_include_directories(A PUBLIC ./)
    

    Note that by using target_include_directories, you tell CMake to include the directories for the libraries automatically later on. This will be useful below.

    In the folder Test

    Now this becomes quite easy:

    set(TEST_EXE_NAME test)
    add_executable(${TEST_EXE_NAME} test.cpp)
    target_include_directories(${TEST_EXE_NAME} PUBLIC ./)
    target_link_libraries(${TEST_EXE_NAME} A B C D)
    add_test(NAME "testDatabase" COMMAND ${TEST_EXE_NAME})
    

    Note that there is no need to set the include directories for A-D here, since CMake already knows from before that they are needed!