最佳做法是创建一个包含基本代码的共享库。然后,您只需在节点中使用此库中的函数/类。
在您的 CMakeLists.txt 中,您可以通过以下方式定义库:
## LIBRARIES: libraries you create in this project that dependent projects also need
catkin_package(
INCLUDE_DIRS include
LIBRARIES <library name>
)
...
## Declare a C++ library
add_library(<library name>
src/${PROJECT_NAME}/<cpp file of your library>
< ... additional files ... >
)
当然不要忘记你需要将依赖项链接到库。
target_link_libraries(${PROJECT_NAME}
${catkin_LIBRARIES}
)
我还建议您通读 CMakeLists.txt,其中包含有关声明库的所有说明。
至于结构,你如何包装它并不重要。在您的特定情况下,我建议您使用一个带有库和两个节点的 catkin 包(一个包中可以有多个节点)。如果您认为需要将库放在单独的包中,那就继续吧。你只需要 include 告诉 catkin 你想要包含那个包作为你想要使用它的包的依赖。你可以通过写来做到这一点
find_package(catkin REQUIRED COMPONENTS
...
<name of the package with the library>
...
)
然后,您只需将包中的标头包含在您的节点(或其他)文件 (C++) 中。如果您的库不仅仅是标题,那么不要忘记将库链接到您的节点与
target_link_libraries(
<node name>
${catkin_LIBRARIES}
<library name>
...
)
我还建议在ros wiki 阅读有关此主题的更多信息。