ROS编程规范
  • Packages, Topics / Services, 文件、库的命名都采用 under_scored

  • Classes / Types的命名采用 CamelCased,比如class ExampleClass, class HokuyoURGLaser。 函数命名采用 camelCased,比如int exampleMethod(int example_arg)

  • 普通变量和成员变量命名、命名空间都使用 under_scored,循环中的临时变量使用i,j,k,i on the outer loop, j on the next inner loop

  • 常量命名采用 ALL_CAPITALS

  • 全局变量采用 g_ 开头的 under_scored

  • 每行最多120个字符

  • 所有头文件要包含#ifndef,比如:

1
2
3
4
#ifndef PACKAGE_PATH_FILE_H
#define PACKAGE_PATH_FILE_H
......
#endif

这部分应该在license之后,#endif在头文件的最后

  • 不使用宏

预处理所用的宏,比如

1
2
3
#if DEBUG
temporary_debugger_break();
#endif

  • 函数的输出参数使用指针,而不是引用: int exampleMethod(FooThing input, BarThing* output);

  • 头文件里不要用using namespace关键字,在源文件里可使用using,但不要using namespace std;,而是使用using std::list;, using std::vector;,否则引入了std所有内容。

  • 建议使用Exceptions,而不是returning integer error codes。 析构函数不要抛出异常。 不直接触发的回调函数,不要抛出异常。

  • 保证代码是 exception-safe: When your code can be interrupted by exceptions, you must ensure that resources you hold will be deallocated when stack variables go out of scope. In particular, mutexes must be released, and heap-allocated memory must be freed. Accomplish this safety by using the following mutex guards and smart pointers

枚举

1
2
3
4
5
6
7
8
9
10
namespace Choices
{
enum Choice
{
Choice1,
Choice2,
Choice3
};
}
typedef Choices::Choice Choice;

This prevents enums from polluting the namespace they’re inside. Individual items within the enum are referenced by: Choices::Choice1, but the typedef still allows declaration of the Choice enum without the namespace.

  • If you are using C++11 and above, you can use scoped enumeration
1
2
3
4
5
6
7
enum class Choice
{
Choice1,
Choice2,
Choice3
};
Choice c = Choice::Choice1;
  • 不建议使用全局变量和函数,尤其前者。更不能在多线程中使用。大多数变量和函数都该在类的体内,其他应当在命名空间里。

  • 类不要使用静态变量。

  • 只在 well-defined exit point 调用exit()函数

  • 使用assertions之类的比条件判断语句好,比如ROS_ASSERT, ROS_ASSERT_MSG, ROS_ASSERT_CMD, ROS_BREADK

Depending on compilation settings, the assertion may not be executed.

It is typical to develop software with assertion-checking enabled, in order to catch violations. When nearing software completion and when assertions are found to always be true in the face of extensive testing, you build with a flag that removes assertions from compilation, so they take up no space or time.

The following option to catkin_make will define the NDEBUG macro for all your ROS packages, and thereby remove assertion checks.
catkin_make -DCMAKE_CXX_FLAGS:STRING="-DNDEBUG"

Note: cmake will rebuild all your software when you run it with this command, and will remember the setting through subsequent catkin_make runs until you delete your build and devel directories and rebuild.