c/c++编码规范 - 头文件

来自Google

http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Classes


1, 使用#define防止重复包含

如果头文件在项目foo的文件夹bar下面,头文件名称是baz.h,那么定义为这样:

#ifndef FOO_BAR_BAZ_H_
#define FOO_BAR_BAZ_H_

...

#endif  // FOO_BAR_BAZ_H_

2, 如果前置声明可以解决依赖,就不要用头文件包含(KISS)

//#include "otherclass.h"
//#include "anohterclass.h"

class OtherClass;
class AnotherClass;

class Sample{
    OtherClass * m_pOhter;
    AnotherClass * m_pAnother;
    static OtherClass m_sOther;
    const OtherClass & m_other;
    void Use(OtherClass po);
};
这几个情况都可以使用前置声明解决依赖,因为编译Sample的时候并不需要知道其他类的定义和尺寸。不要再头文件里包含头文件,除非万不得已(继承等),当然.cc文件里面想怎么包含就怎么包含吧。

3,内联函数

小的内联可以减少程序的整个尺寸,反之亦然。建议:函数超过10行,就最好不要内联了。如果内联里面有循环和分支,最好也不要内联了,不划算。


4,-inl.h头文件

可以把一些实现代码放在这里,但是呢,不要像cpp那样单独参与编译(只有被某些cpp包含起来间接参与编译才可以成功的代码)。


MISRA的一些c/c++编码建议:

另存为(zip)

http://hi.csdn.net/attachment/201202/23/0_13300094632KhX.gif

你可能感兴趣的:(c/c++编码规范 - 头文件)