ROS2 C++ 패키지 작성법

OpenJR·2025년 4월 16일

1. C++ 패키지 생성

공식 튜토리얼에서는 간단하게만 알려주는데, 보통 아래 내용이 들어가면 좋다.
추가한 내용은 패키지 저자의 이름과 이메일, 라이센스, 패키지 설명인데 회사에서 만약 ROS2를 사용한다면 어차피 package.xml에 해당 내용을 적어줘야 하기 때문에 미리 적어주는게 좋다.
뭐 안해도 죽지는 않는데, 또 굳이 안할 필요도 없는 것 같다. (정보는 많으면 많을수록 좋다)

ros2 pkg create --build-type ament_cmake \
--license Apache-2.0 \
--description <description> \
--dependencies rclcpp <packages> \
--maintainer-email <e-mail> \
--maintainer-name 'Name' \
<Node Name>

2. 기본 ROS 폴더 구조 작성

나의 경우 아래 처럼 구조 생긴다.

.
├── CMakeLists.txt
├── include
│   └── fire_model_publisher
├── LICENSE
├── package.xml
└── src

include/fire_model_publisher 폴더와 src폴더만 생성되는데, 각 폴더 안에 파일은 만들어줘야 아래처럼 만들어 줘야한다.

.
├── CMakeLists.txt
├── include
│   └── fire_model_publisher
│       └── publisher.hpp # 내가 작성
├── LICENSE
├── package.xml
└── src
    ├── main.cc # 내가 작성
    └── publisher.cc # 내가 작성

보통 간단한 구조는 저렇게 되고 복잡한 구조는 아래처럼 될 수도 있다.

.
├── CMakeLists.txt
├── include
│   └── fire_model_publisher
│       └── module1
│           └── module1.hpp
│       └── module2
│           └── module2.hpp
├── LICENSE
├── package.xml
└── src
    └── module1
        └── module1.cc
    └── module2
        └── module2.cc
    └── main.cc

3. CMakeLists.txt 작성

맨 처음 패키지를 생성할때 디펜던시를 잘 넣어 줬으면 보통 아래 처럼 씨메이크 파일이 생성된다.

cmake_minimum_required(VERSION 3.8)
project(fire_model_publisher)

if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
  add_compile_options(-Wall -Wextra -Wpedantic)
endif()

# find dependencies
find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)
find_package(visualization_msgs REQUIRED)

if(BUILD_TESTING)
  find_package(ament_lint_auto REQUIRED)
  # the following line skips the linter which checks for copyrights
  # comment the line when a copyright and license is added to all source files
  set(ament_cmake_copyright_FOUND TRUE)
  # the following line skips cpplint (only works in a git repo)
  # comment the line when this package is in a git repo and when
  # a copyright and license is added to all source files
  set(ament_cmake_cpplint_FOUND TRUE)
  ament_lint_auto_find_test_dependencies()
endif()

ament_package()

나는 rclcppvisualization_msgs를 디펜던시로 사용해 find_package()함수로 불러오는 것을 볼 수 있는데, 아래 처럼 나는 바꾼다. 바로 ament_cmake_auto를 사용하는 것인데, ament_auto_find_build_dependencies()를 사용하면 자동으로 package.xml에 있는 디펜던시를 알아서 불러준다. 또한 ament_auto_add_library, ament_auto_add_executable, ament_auto_package를 사용해 복잡한 과정을 단순화 할 수 있는데 좋은 ROS2 패키지 이다.

find_package(ament_cmake_auto REQUIRED)
ament_auto_find_build_dependencies()

ament_auto_add_library(fire_model_publisher SHARED
  src/publisher.cc
)
target_include_directories(fire_model_publisher PUBLIC
  include
)

ament_auto_add_executable(fire_model_publisher_node src/main.cc)
target_link_libraries(fire_model_publisher_node
  fire_model_publisher
)

ament_auto_package(INSTALL_TO_SHARE
  config
  launch
  meshes
)
profile
Jacob

0개의 댓글