Include header file from subdirectorie cmake

Given this tree:

Project
| CmakeLists.txt
| File1
|| CMakeLists.txt
|| include 
|||file1.h
|| src
|||file1.cpp
|||main.cpp
| File2
|| CMakeLists.txt
|| include 
|||file2.h
|| src
|||file2.cpp
|||main.cpp
| Core
|| core.h
|| CMakeLists.txt
|build
||"build files"

I would like to link the core.h to file1.h and file2.h, but what I currently have does not appear to work
PROJECT CMakeLists.txt

cmake_minimum_required(VERSION 3.27.7)

project(file1)
project(file2)

add_subdirectory(file1)
add_subdirectory(file2)
add_subdirectory(core)

set_target_properties(core PROPERTIES LINKER_LANGUAGE CXX)

target_include_directories(file1 PUBLIC core)
target_include_directories(file2 PUBLIC core)
target_link_directories(file1 PRIVATE Core/)
target_link_directories(file2 PRIVATE Core/)
target_link_libraries(file1 core)
target_link_libraries(file2 core)

FILE1 CMakeLists.txt

cmake_minimum_required(VERSION 3.27.7)

project (file1)

set(SOURCES src/file1.cpp src/main.cpp)

add_executable(file1 ${SOURCES})

target_include_directories(file1 PRIVATE ${PROJECT_SOURCE_DIR}/include)

target_link_libraries(file1 core)

FILE2 CMakeLists.txt

cmake_minimum_required(VERSION 3.27.7)

project (file2)

set(SOURCES src/file2.cpp src/main.cpp)

add_executable(file2 ${SOURCES})

target_include_directories(file2 PRIVATE ${PROJECT_SOURCE_DIR}/include)

target_link_libraries(file2 core)

Core CMakeLists.txt

add_library(core STATIC core.h)
include_directories(core.h)
target_include_directories(core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})

I`m trying to include core.h into file1.h and file2.h.

When I build this I get this errors:
LINK : fatal error LNK1104: cannot open file '..\Core\Debug\core.lib' [\blah\blah\build\file1\file1.vcxproj] and
LINK : fatal error LNK1104: cannot open file '..\Core\Debug\core.lib' [\blah\blah\build\file2\file2.vcxproj]

What am I doing incorrectly?

I do not know what to do

You cannot create STATIC directories purely from header files. Change to an INTERFACE library.

Since you used the PUBLIC modifier when setting core‘s include directories, linking the file1 and file2 targets to core will automatically set the include directories, so you need neither the target_include_directories or target_link_directories commands.

Leave a Comment