0

I have compiled library "libmodbus" to "libmodbus.dll" in path "third-party/libmodbus/bin" and its sources in "third-party/libmodbus/src". I would like to add this library to my Cmake project which is to make my own library. For this purpose, I added the following commands in CMakeList.txt.

cmake_minimum_required(VERSION 3.1)

set(PROJECT_NAME MyLib)
set(LIB_NAME MyLib)

project(${PROJECT_NAME} VERSION 0.1.0)

set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

set(SRC_DIR src/)

add_compile_options(-g -Wall -Wextra -pedantic)

include_directories(third-party/libmodbus/src)
link_directories(third-party/libmodbus/bin)

set(HEADERS
    ${SRC_DIR}/x.h    )

set(SOURCES 
    ${SRC_DIR}/x.cpp    )

add_library(${LIB_NAME} SHARED ${HEADERS} ${SOURCES})

target_link_libraries(${LIB_NAME} PUBLIC modbus)

target_include_directories(${LIB_NAME} PUBLIC src)

I am able to add "#include <modbus.h>" without error, but when I try to use the structure defined in this file I get error "error: Unknown type name 'modbus_t'". Did I connect the library to the project correctly? I also have a project in Qmake that uses the same library and it doesn't have this problem. The library is written in C.

  • You can use an "IMPORTED" library, with add_library. See https://cmake.org/cmake/help/latest/command/add_library.html#imported-libraries – André Aug 29 '23 at 07:58
  • Does this answer your question? [CMake link to external library](https://stackoverflow.com/questions/8774593/cmake-link-to-external-library) – André Aug 29 '23 at 08:05
  • I would write an answer but a bit lazy to try it on Windows. In principle after compiling the `libmodbus` you should install it somewhere. Then in the install dir you will have directories with the headers and libraries. `libmodbus` comes with `libmodbus.pc` so you can integrate it in your `CMakeLists.txt` with `pkg_check_modules(modbus REQUIRED IMPORTED_TARGET GLOBAL modbus)` which will create a target `PkgConfig::modbus` for you. Remember to set `PKG_CONFIG_PATH` to point to your modbus directory. – pptaszni Aug 29 '23 at 08:12
  • The error message is about your C++ code, which probably forgot to use `#include` for getting definition of `modbus_t` type. Without looking into your code (in form of [mcve]) we cannot help you. – Tsyvarev Aug 29 '23 at 08:44

0 Answers0