ros入门(1)—如何添加一个msg

如何创建一个msg文件,然后自动编译成所需的头文件(c++)在你的代码中使用?因为msg,srv,action类似,文中介绍msg时会有交叉。
例如,如何添加一个MsgTutorial.msg,然后生成MsgTutorial.h,在你的代码中去使用?

#include "ros_tutorials_topic/MsgTutorial.h"

创建msg文件

在package中的msg目录下,创建MsgTutorial.msg

int32 data

修改package.xml

在package.xml中定义编译和运行msg所需,即message_generation和message_runtime。

Your package.xml must declare a on message_generation, and a on message_runtime:

<build_depend>message_generation</build_depend>
<exec_depend>message_runtime</exec_depend>

那么message_generation的作用是什么?就是用来生成特定语言的messages。

Package modeling the build-time dependencies for generating language bindings of messages

修改CMakeLists.txt

For CMake, find the catkin packages for message_generation and any messages, services or actions you depend on:

find_package(catkin REQUIRED COMPONENTS message_generation std_msgs)

在创建action的时候,需要添加actionlib_msgs依赖,
For building actions, include actionlib_msgs among the dependencies:

find_package(catkin REQUIRED
             COMPONENTS
             actionlib_msgs
             message_generation
             std_msgs)

添加msg文件,
Next, list your message definitions:

add_message_files(
   FILES
   MsgTutorial.msg
)

Then, generate all your message, service and action targets with this command:

generate_messages(DEPENDENCIES std_msgs)

catkin_package()中要声明你的msg依赖的其他包中的东东
Make sure the catkin_package() command declares your message, service and action dependencies for other packages:

catkin_package(CATKIN_DEPENDS message_runtime std_msgs)

A good ROS practice is to collect related messages, services and actions into a separate package with no other API. That simplifies the package dependency graph.

比较好的实践是怎么做的?将msg,srv,action定义在一个独立的package中,但是如果你要在你的代码中即定义了msg,然后又要使用这些msg,就必须先把msg编译完成,即先把msg生成头文件(c++)。

However, you can provide scripts and programs with the message package. If you do, message generation targets need to be built before any programs that depend on them.

需要进行下面的声明。
Every target that directly or indirectly uses one of your message headers must declare an explicit dependency:

add_dependencies(your_program ${${PROJECT_NAME}_EXPORTED_TARGETS})

If your build target also uses message or service headers imported from other catkin packages, declare those dependencies similarly:

add_dependencies(your_program ${catkin_EXPORTED_TARGETS})

最后,需要告诉你的应用程序,链接了哪些库。
Use the target_link_libraries() function to specify which libraries an executable target links against. This is done typically after an add_executable() call.

target_link_libraries的用法如下,

target_link_libraries(<executableTargetName>, <lib1>, <lib2>, ... <libN>)

一个例子,foo这个可执行文件,依赖于libmoo.so,

add_executable(foo src/foo.cpp)
add_library(moo src/moo.cpp)
target_link_libraries(foo moo)  -- This links foo against libmoo.so

如果在创建package的时候,依赖了roscpp,在最终编译的CMakeLists.txt中就需要添加catkin_LIBRARIES的依赖。

target_link_libraries(my_program ${catkin_LIBRARIES})

猜你喜欢

转载自blog.csdn.net/lewif/article/details/79866229
今日推荐