ROS2 的包必须在 src
文件夹下,使用下面的命令创建一个包,并设置相关的依赖
ros2 pkg create my_package --dependencies rclcpp std_msgs
可以打开包内的 package.xml
,查看 depend
有哪些依赖
#include "rclcpp/rclcpp.hpp"
int main(int argc,char *argv[])
{
rclcpp::init(argc,argv);
auto node = rclcpp::Node::make_shared("simple_node");
rclcpp::spin(node);
rclcpp::shutdown();
return 0;
}
rclcpp::Node
包含了很多等价的别名以及静态方法,SharedPtr
是 std::shared ptr<rclcpp::Node>
的别名,而 make_shared
是它的静态方法。该行代码创建了一个名字叫 simple_node
的节点,在程序中以 node
表示该节点spin
可以阻止代码的执行,防止他立即终止shutdown
管理节点的关闭接下来,来看看CMake文件
cmake_minimum_required(VERSION 3.8)
project(my_package)
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(std_msgs REQUIRED)
set(dependencies
rclcpp
)
add_executable(simple src/simple.cpp)
ament_target_dependencies(simple ${dependencies})
install(TARGETS
simple
ARCHIVE DESTINATION lib
LIBRARY DESTINATION lib
RUNTIME DESTINATION lib/${PROJECT_NAME}
)
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_export_dependencies(${dependencies})
ament_package()
之后编译并运行
colcon build --symlink-install
ros2 run my_packkage simple
由于使用了 spin
因此程序并没有执行任何内容