Skip to content

Improve CMake integration for add_subdirectory consumers#15

Open
ros-dorian wants to merge 5 commits into
serhmarch:mainfrom
ros-dorian:feature/cmake_improvements
Open

Improve CMake integration for add_subdirectory consumers#15
ros-dorian wants to merge 5 commits into
serhmarch:mainfrom
ros-dorian:feature/cmake_improvements

Conversation

@ros-dorian

Copy link
Copy Markdown

Hi @serhmarch , thank you for sharing your work! Really useful and well written.

I encountered a few quirks while integrating your library in a project using CMake's add_subdirectory.

Description

Although ModbusLib builds fine standalone, integrating it as a subproject (git submodule, cmake add_subdirectory) is not as straight forward for the following reasons:

  • The project's CMake target does not propagate an include directory, must be done manually
  • Modbus_config.h is generated into the source tree, leading to a dirty submodule status
  • Linkage type is tied to the global BUILD_SHARED_LIBS. No fine control possible

Solution

Here are the fixes that I made to address each of the points above:

  • Add a target_include_directories for the modbus target with the relevant paths
  • Move the generated Modbus_config.h from the source tree to the build tree (and add it to .gitignore), making sure it is reachable from the target's include directories
  • Introduce MB_BUILD_SHARED to selectively build shared/static libraries. It defaults to BUILD_SHARED_LIBS to not break current behavior.

Result

Here is a concrete example. The code below integrates the ModbusLib inside an existing CMake project, forcing static linkage:

set(_saved_bsl ${BUILD_SHARED_LIBS})
set(BUILD_SHARED_LIBS OFF)

add_subdirectory(ModbusLib)
target_include_directories(modbus PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/ModbusLib/src)

set(BUILD_SHARED_LIBS ${_saved_bsl}) # restore original value to avoid affecting other libs

target_link_library(myLib modbus)

Now with the fixes applied:

set(MB_BUILD_SHARED OFF)
add_subdirectory(ModbusLib)

target_link_library(myLib modbus::modbus)

Notes

  • I did not update the QMake modbus.pro file, looking at the history it does not look like it is actively maintained. Let me know if it still needs to be supported (I'm not really familiar with QMake however).

Environment

ModbusLib v0.5.0
Windows 11, Visual Studio 2026

@ros-dorian ros-dorian changed the title Feature/cmake improvements Improve CMake integration for add_subdirectory consumers Jun 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant