Building and using a library in ROS2

asked 2020-07-14 03:12:00 -0500

KenYN gravatar image

Given a project like this:

proj
    + main
        - CMakeLists.txt
    + mylib
        - CMakeLists.txt
        + sub_module1
            - CMakeLists.txt
        + sub_module2
            - CMakeLists.txt

The mylib/CMakeLists.txt is a catch-all that ROS-ifies the two sub_modules:

# Boiler-plate like this, etc
find_package(ament_cmake REQUIRED)

add_subdirectory(sub_module1)
add_subdirectory(sub_module2)

ament_export_include_directories(include)
install(DIRECTORY sub_module1/include/ sub_module2/include_copy/
        DESTINATION include)
ament_package()

The sub_module1 looks like this - the CMakeLists.txt is mostly generic non-ROS building with a little ament tacked on at the end:

project(sub_module1)
# Usual CMake stuff
add_library(${PROJECT_NAME} SHARED
  ${SOURCES})

target_include_directories(${PROJECT_NAME} PRIVATE
    ${HEADERS})

if(ament_cmake_FOUND)
    ament_export_targets(export_${PROJECT_NAME})
    ament_export_libraries(${PROJECT_NAME} HAS_LIBRARY_TARGET)
    ament_export_dependencies(${PROJECT_NAME})

    install(TARGETS ${PROJECT_NAME}
            EXPORT export_${PROJECT_NAME}
            ARCHIVE DESTINATION lib
            LIBRARY DESTINATION lib
            RUNTIME DESTINATION bin
            INCLUDES DESTINATION include
    )
endif()

Now, in main I want to link againstmylib::sub_module1:

# Usual stuff
find_package(mylib REQUIRED COMPONENTS sub_module1)

This on its own doesn't work, and everything else I've tried has failed, like target_link_libraries(${PROJECT_NAME} mylib::sub_module1) as when I run the project I always get an undefined symbol from the sub_module1. I'm sure I'm missing something simple, but what?

edit retag flag offensive close merge delete