Home > Software design >  CMake include header file in different directory
CMake include header file in different directory

Time:10-19

So I have a directory that's formatted as follows:

Project: 
- src 
   - a.cpp 
   - b.cpp 
   - c.cpp 
- include 
   - h.cpp 
   - h.hpp

How would I get CMake to include h.hpp in the files in the source folder? I tried doing include_directories(include) but CMake is still unable to find the file. I also tried changing the include directive in a.cpp to #include "../include/h.hpp". However, none of these solutions have worked.

EDIT:

The output is:

[build] Consolidate compiler generated dependencies of target a
[build] Consolidate compiler generated dependencies of target c
[build] Consolidate compiler generated dependencies of target b
[build] [ 16%] Building CXX object CMakeFiles/b.dir/src/b.cpp.o
[build] [ 33%] Building CXX object CMakeFiles/c.dir/src/c.cpp.o
[build] [ 50%] Building CXX object CMakeFiles/a.dir/src/a.cpp.o
[build] [ 66%] Linking CXX executable a
[build] [ 83%] Linking CXX executable c
[build] [100%] Linking CXX executable b
[build] /usr/bin/ld: CMakeFiles/a.dir/src/a.cpp.o: in function `func(...)':
[build] ../a.cpp:55: undefined reference to `func(...)'
[build] /usr/bin/ld: a.cpp:58: undefined reference to `func(...)'

Note that func is a function with an implementation provided in h.cpp.

CMakeLists.txt:

cmake_minimum_required(VERSION 3.17)

set(CMAKE_TOOLCHAIN_FILE ${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake
  CACHE STRING "Vcpkg toolchain file")

project(proj)


find_package(fmt CONFIG REQUIRED)
find_package(CUDAToolkit REQUIRED)

link_libraries(
    fmt::fmt CUDA::nvrtc CUDA::cuda_driver CUDA::cudart
)

include_directories(include)

add_executable(a ${CMAKE_CURRENT_SOURCE_DIR}/src/a.cpp)
add_executable(b ${CMAKE_CURRENT_SOURCE_DIR}/src/b.cpp)
add_executable(c ${CMAKE_CURRENT_SOURCE_DIR}/src/c.cpp)

CodePudding user response:

You should add h.cpp as a source for each executable that uses functions from h.hpp:

add_executable(a ${CMAKE_CURRENT_SOURCE_DIR}/src/a.cpp ${CMAKE_CURRENT_SOURCE_DIR}/include/h.cpp)
add_executable(b ${CMAKE_CURRENT_SOURCE_DIR}/src/b.cpp ${CMAKE_CURRENT_SOURCE_DIR}/include/h.cpp)
add_executable(c ${CMAKE_CURRENT_SOURCE_DIR}/src/c.cpp ${CMAKE_CURRENT_SOURCE_DIR}/include/h.cpp)

As you have said,

func is a function with an implementation provided in h.cpp

so you need to add that implementation to your executables

  • Related