cmakepublictarget-link-libraries

CMake target_link_libraries public inheritance


I am educating myself on a CMakeLists.txt of implot library. The imgui library, which is a library on which implot is based, declares the link libraries to be of type PUBLIC, as shown below.

# ...

add_library(imgui ${IMGUI_HEADERS} ${IMGUI_SRC})
if(MSVC)
  target_compile_options(imgui PRIVATE /W4 /WX /arch:AVX2 /fp:fast)
endif()
target_link_libraries(imgui PUBLIC glfw glad OpenGL::GL imm32)
target_compile_definitions(imgui PRIVATE IMGUI_DLL_EXPORT)

# ...

add_library(implot ${IMPLOT_HEADERS} ${IMPLOT_SRC})
target_link_libraries(implot PUBLIC imgui)
target_compile_definitions(implot PUBLIC IMPLOT_DEBUG IMPLOT_DLL_EXPORT IMPLOT_BACKEND_ENABLE_OPENGL3 IMGUI_IMPL_OPENGL_LOADER_GLAD)
set_property(TARGET implot PROPERTY CXX_STANDARD 11)
if(MSVC)
  target_compile_options(implot PRIVATE /W4 /WX /arch:AVX2 /fp:fast /permissive-) 
else()
  target_compile_options(implot PRIVATE -Wall -Wextra -pedantic -Werror -mavx2 -Ofast)
endif()

Since imgui is PUBLICly linked against glfw, glad, OpenGL::GL, imm32, does it mean that implot and whoever that uses implot will also be PUBLICly linked against glfw, glad, OpenGL::GL, imm32?

Is the reason behind this because of imgui being a shared library?


Solution

  • Since imgui is PUBLICly linked against glfw, glad, OpenGL::GL, imm32, does it mean that implot and whoever that uses implot will also be PUBLICly linked against glfw, glad, OpenGL::GL, imm32?

    Yes, it is. More details could be found in the official documentation in the section Build Specification and Usage Requirements.

    Is the reason behind this because of imgui being a shared library?

    Yes, it is. Since add_library() does not have any SHARED or STATIC named parameter, a user may decide to build it statically by providing -DBUILD_SHARED_LIBS:BOOL=OFF cmake(1) parameter. So to link with it, a linker needs all the dependencies list. And this is a good practice to give him a choice on how to build your project ;-)