11.3 编译nodes

之前教程中使用 catkin_create_pkg 创建了 package.xmlCMakeLists.txt 文件。

cmake_minimum_required(VERSION 2.8.3)
project(beginner_tutorials)

## Find catkin and any catkin packages
find_package(catkin REQUIRED COMPONENTS roscpp rospy std_msgs genmsg)

## Declare ROS messages and services
add_message_files(DIRECTORY msg FILES Num.msg)
add_service_files(DIRECTORY srv FILES AddTwoInts.srv)

## Generate added messages and services
generate_messages(DEPENDENCIES std_msgs)

## Declare a catkin package
catkin_package()

CMakeLists.txt 文件末尾加入几条语句:

include_directories(include ${catkin_INCLUDE_DIRS})

add_executable(talker src/talker.cpp)
target_link_libraries(talker ${catkin_LIBRARIES})

add_executable(listener src/listener.cpp)
target_link_libraries(listener ${catkin_LIBRARIES})

最后,CMakeLists.txt 文件看起来大概是这样:

cmake_minimum_required(VERSION 2.8.3)
project(beginner_tutorials)

## Find catkin and any catkin packages
find_package(catkin REQUIRED COMPONENTS roscpp rospy std_msgs genmsg)

## Declare ROS messages and services
add_message_files(FILES Num.msg)
add_service_files(FILES AddTwoInts.srv)

## Generate added messages and services
generate_messages(DEPENDENCIES std_msgs)

## Declare a catkin package
catkin_package()

## Build talker and listener
include_directories(include ${catkin_INCLUDE_DIRS})

add_executable(talker src/talker.cpp)
target_link_libraries(talker ${catkin_LIBRARIES})
add_dependencies(talker beginner_tutorials_generate_messages_cpp)

add_executable(listener src/listener.cpp)
target_link_libraries(listener ${catkin_LIBRARIES})
add_dependencies(listener beginner_tutorials_generate_messages_cpp)

这会生成两个可执行文件talkerlistener, 默认存储到 devel space 目录下,具体是在~/catkin_ws/devel/lib/<package name> 中.

现在要为可执行文件添加对生成的消息文件的依赖:

add_dependencies(talker beginner_tutorials_generate_messages_cpp)

这样就可以确保自定义消息的头文件在被使用之前已经被生成。因为 catkin 把所有的 package 并行的编译,所以如果你要使用其他 catkin 工作空间中其他 package 的消息,你同样也需要添加对他们各自生成的消息文件的依赖。

如果需要关于 CMakeLists.txt 更详细的信息,请参考 catkin/CMakeLists.txt

现在运行 catkin_make:

# In your catkin workspace$ catkin_make

注意:如果你是添加了新的 package,你需要通过--force-cmake 选项告诉 catkin 进行强制编译。参考 catkin/Tutorials/using_a_workspace#With_catkin_make

既然已经编写好了发布器和订阅器,下面让我们来测试消息发布器和订阅器。

Last updated