Search code examples
c++cmakeimgui

Make it possible to use imports of the whole project in the catalog CMake


I want to make a small application using imgui

To run the test window I use the opengl glfw backend

The problem is that the files in the lib/ imgui_gl directory of my project can't access the headers that the file at the root of the project has access to

CMake problem

This is what my CmakeList file looks like

cmake_minimum_required(VERSION 3.17)
project(boardserver)

set(CMAKE_CXX_STANDARD 20)
set(LIB_FOLDER ${CMAKE_CURRENT_SOURCE_DIR}/lib) # Lib folder


add_executable(boardserver main.cpp)

find_package(imgui CONFIG REQUIRED)
find_package(GLEW REQUIRED)
find_package(OpenGL REQUIRED)
find_package(SDL2 REQUIRED)
find_package(glfw3 REQUIRED)

## Imgui opengl glfw backend lib
set(imgui-gl_Includes "${LIB_FOLDER}/imgui_gl/")
add_library(imgui-gl STATIC
        ${LIB_FOLDER}/imgui_gl/imgui_impl_glfw.cpp ${LIB_FOLDER}/imgui_gl/imgui_impl_opengl3.cpp )


include_directories(${imgui-gl_Includes})
target_link_libraries(boardserver PRIVATE imgui::imgui GLEW::GLEW OpenGL::GL SDL2::SDL2 glfw imgui-gl)

Solution

  • You need to tell CMake to link imgui-gl with the imgui::imgui target so it knows where to find imgui.h too:

    target_link_libraries(imgui-gl PUBLIC imgui::imgui)
    

    As modern CMake best practice, you may also want to make its include directory part of the interface:

    target_include_directories(imgui-gl PUBLIC "${LIB_FOLDER}/imgui_gl")
    

    Together, these statements ensure that any target that links to imgui-gl sees both the correct headers and knows what to link to.