简体   繁体   English

头文件的C ++样式

[英]C++ style for header files

Suppose I have the following files: 假设我有以下文件:

  1. main.cpp main.cpp
  2. routine.cpp 例程
  3. routine.h 例行程序

Suppose further that main.cpp calls a function routine() that is defined in routine.cpp, but routine.cpp also contains functions that are only used by the routine() function. 进一步假设main.cpp调用了routine()中定义的函数,但是routine() .cpp还包含routine()函数使用的函数。 In other words, routine.cpp contains both functions that are only called from within routine.cpp and functions that are called from other source files. 换句话说,例程.cpp包含仅从例程.cpp中调用的函数和从其他源文件中调用的函数。

Obviously main.cpp will contain #include "routine.h" . 显然main.cpp将包含#include "routine.h" But should routine.h contain prototypes of all functions that are defined in routine.cpp (style A), or should routine.h only contain prototypes of functions that are called from other source files (style B)? 但是,routine.h应该包含在例程.cpp中定义的所有函数的原型(样式A),还是例程.h应该包含从其他源文件调用的函数的原型(样式B)?

I've always written code after style A, but recently I've wondered if style B makes more sense stylistically. 我总是在样式A之后编写代码,但是最近我想知道样式B是否在样式上更有意义。 (If style B is used, then the prototypes of the functions that are used only inside routine.cpp could be at the top of routine.cpp, or the definitions could simply precede their usage.) (如果使用样式B,则仅在例程.cpp内使用的函数的原型可以位于例程.cpp的顶部,或者可以仅在其用法之前定义。)

Usually, the header only contains methods of the public interface (if those are free functions). 通常,标头仅包含公共接口的方法(如果这些方法是自由函数)。 You can declare the auxiliary methods used in routine.cpp in an anonymous namespace. 您可以在匿名名称空间中声明routine.cpp中使用的辅助方法。

//routine.h

void foo();
void goo();

//routine.cpp

namespace
{
   void fooHelper() {}
   void gooHelper() {}
}

void foo()
{
   fooHelper();
}
void goo()
{
   gooHelper();
}

Such functions were previously declared static , which gave them internal linkage, but the general style now is to use anonymous namespaces. 以前将此类函数声明为static ,从而为它们提供了内部链接,但现在的通用样式是使用匿名名称空间。

Google's style guide is very comprehensive. Google的风格指南非常全面。 It provides pros/cons and justification for their choices. 它提供了优点/缺点和选择依据。 http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml

例行程序.h不应包含不打算在例行程序.cpp(样式B)之外使用的那些函数的声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM