Search code examples
c++ccmakecompiler-errorsheader-files

CMake: can't find my header file in a different directory


I have a CMake project with these relevant folders:

project_folder
-src
|--main.c
peripherals
|--something.h
|--something.c

My CMake in project_folder includes:

add_subdirectory(peripherals)

if (NOT $ENV{TARGET_SOURCES} STREQUAL "")
    target_sources(app PRIVATE $ENV{TARGET_SOURCES})
else()
    target_sources(app PRIVATE src/main.c)
endif()

My CMake under peripherals incudes:

add_library (peripherals something.c)

target_include_directories (peripherals PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})

CMake under src:

add_executable(app main.c)
target_link_libraries(app PRIVATE peripherals)

My project is building fully but when I try to include my header file in main.c I get:

project_folder/peripherals/something.h:No such file or directory

In my main.c file I have #include "peripherals/something.h". Does anyone know how to fix this? I'm not sure if my #include statement is correct and I think I am missing stuff in my CMakeLists files


Solution

  • You can either do "#include "../peripherals/i2c_test.h" in your main.cpp

    OR

    in your CMake in project_folder:

     target_include_directories(app ${CMAKE_CURRENT_SOURCE_DIR})
    

    and then in main.c:

    #include <peripherals/i2c_test.h>
    ....