Hello,
I have very little experience with CMake and I am trying to set up a simple library.
The library depends on other external libraries and adds them using the add_subdirectory and target_link_library commands.
Everything compiles, builds, and runs fine. But, I can only include the external library header files either in the source files specified in target_sources or in my library’s header files that are included in those source files. If I have a stand-alone header file, I cannot include any of the external library header files in it.
This is my root CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(Ivory)
set(CMAKE_CXX_STANDARD 20)
add_library(${PROJECT_NAME} SHARED)
# Determine compiler platform (x32 or x64)
math(EXPR PLATFORM_BITS "8*${CMAKE_SIZEOF_VOID_P}")
set(PLATFORM "x${PLATFORM_BITS}")
# Determine target build platform
target_compile_definitions(${PROJECT_NAME}
PUBLIC
IVORY_WINDOWS
PRIVATE
IVORY_BUILD_DLL
)
# Set output directory
set(OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/bin/${CMAKE_SYSTEM_NAME}-${CMAKE_BUILD_TYPE}-${PLATFORM})
# Subdirectories
add_subdirectory(src)
add_subdirectory(tests)
add_subdirectory(executables)
target_include_directories(${PROJECT_NAME} PUBLIC include)
# External Libraries #
set(BUILD_SHARED_LIBS OFF)
# GLM
add_subdirectory(lib/glm)
target_link_libraries(${PROJECT_NAME} PRIVATE glm)
# GLEW
add_subdirectory(lib/glew)
target_link_libraries(${PROJECT_NAME} PRIVATE libglew_static)
# SFML
add_subdirectory(lib/SFML)
target_link_libraries(${PROJECT_NAME} PRIVATE sfml-window sfml-audio)
# SPDLOG
add_subdirectory(lib/spdlog)
target_link_libraries(${PROJECT_NAME} PRIVATE spdlog)
# MinGW
target_link_libraries(${PROJECT_NAME} PRIVATE -static)
# Output Location
set_target_properties(${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${OUTPUT_DIRECTORY})
This is my src folder CMakeLists.txt
target_sources(${PROJECT_NAME}
PRIVATE
Application.cpp
)
And this is my folder structure
EDIT
I solved the issue. Because the header file is meant to be included by users of the library, that means the libraries this header file depends on should be linked as PUBLIC so that the client can also see them. The change I had to make is instead of target_link_libraries(${PROJECT_NAME} PRIVATE lib) do target_link_libraries(${PROJECT_NAME} PUBLIC lib)