Home > front end >  CMake can't find file or directory
CMake can't find file or directory

Time:11-06

I'm working on a CMake project with multiple subdirectories and I can't get it to work. My working directory is the following:

├───main.cpp
├───CMakeLists.txt
├───build
├───States
    └───CMakeLists.txt
└───Elevator
    ├───CMakeLists.txt

Once I build the project, I get Elevator/Elevator.h: No such file or directory as an error. The way my project is set up, Elevator is included in States and apparently CMake isn't linking them properly.

My root CMakeLists.txt:

cmake_minimum_required(VERSION 3.21.4)
project(Test)
set(CMAKE_CPP_STANDARD 11)
set(CMAKE_CPP_STANDARD_REQUIRED True)

add_subdirectory(Elevator)
add_subdirectory(States)

add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} PUBLIC Elevator States)

The one in Elevator:

set(elevator_source_files
  Elevator.cpp
  Elevator.h
  Set.cpp
  Set.h
)

add_library(Elevator ${elevator_source_files})

The CMakeLists.txt in States:

set(state_source_files
  State.h
  State.cpp
  InitialState.h
  InitialState.cpp
  EmergencyState.cpp
  EmergencyState.h
  IdleState.h
  IdleState.cpp
  MaintenanceState.h
  MaintenanceState.cpp
  MovingState.h
  MovingState.cpp
  AllStates.h
  FSM.h
  FSM.cpp

)

add_library(States ${state_source_files})
target_include_directories(States PUBLIC ${CMAKE_CURRENT_LIST_DIR}/..)
target_link_libraries(States PUBLIC Elevator)

I'm still a novice so any help would be appreciated! It's worth noting that States.h includes Elevator with #include "Elevator/Elevator.h"

UPDATE: The project now builds and runs. I updated the CMake files in the description.

CodePudding user response:

For #include "Elevator/Elevator.h" to work in the States library you need to include the folder containing the Elevator folder.

One way to fix this is to change

target_include_directories(States PUBLIC ${CMAKE_CURRENT_LIST_DIR})

to

target_include_directories(States PUBLIC ${CMAKE_CURRENT_LIST_DIR} 
${CMAKE_CURRENT_LIST_DIR}/..)

to have CMake add the State folder and its parent to the include directories.

  • Related