Home >Backend Development >C#.Net Tutorial >Research on the inclusion order of C++ header files

Research on the inclusion order of C++ header files

黄舟
黄舟Original
2017-02-06 14:11:092849browse

one. Viewpoints in the "Google C++ Programming Style Guide"


The company is promoting coding standards, and the leader proposed to basically use the "Google C++ Programming Style Guide". Among them, the "Google C++ Programming Style Guide" has the following order of inclusion of header files:

Names and Order of Includes
link ▽Use standard order for readability and to avoid hidden dependencies:C library, C++ library, other libraries’ .h, your project’s .h.
All of a project’s header files should belisted as descendants of the project’s source directory without use of UNIXdirectory shortcuts . 
(the current directory) or .. (the parent directory). Forexample, google-awesome-project/src/base/logging.h should be included as
#include “base/logging.h”
In dir/foo.cc or dir/foo_test.cc, whosemain purpose is to implement or test the stuff in dir2/foo2.h, order yourincludes as follows:
dir2/foo2.h (preferred location — seedetails below).
C system files.
C++ system files.
Other libraries’ .h files.
Your project’s .h files.
The preferred ordering reduces hiddendependencies. We want every header file to be compilable on its own. 
Theeasiest way to achieve this is to make sure that every one of them is the first.h file #included in some .cc.
dir/foo.cc and dir2/foo2.h are often in thesame directory (e.g. base/basictypes_test.cc and base/basictypes.h), but can bein different directories too.
Within each section it is nice to order theincludes alphabetically.
For example, the includes ingoogle-awesome-project/src/foo/internal/fooserver.cc might look like this:
#include "foo/public/fooserver.h"  // Preferred location.
#include <sys/types.h>
#include <unistd.h>
#include <hash_map>
#include <vector>
#include "base/basictypes.h"
#include"base/commandlineflags.h"
#include "foo/public/bar.h"


Here I will talk about my understanding of the above (if it is inappropriate, please feel free to Please correct me):


1. In order to enhance readability and avoid implicit dependencies, the following order should be used: C standard library, C++ standard library, and other libraries. Header files, header files of your own project. However, the preferred header file is included first, that is, for example, a.cpp file should include a.h first. Prefer header files to reduce hidden dependencies while ensuring that header files and implementation files match. A specific example is: If you have a cc file (the suffix of the cpp file on the Linux platform is cc) which is google-awesome-project/src/foo/internal/fooserver.cc, then the order of the header files it contains is as follows:

#include <sys/types.h>  
#include <unistd.h>  
  
#include <hash_map>  
#include <vector>  
  
#include "base/basictypes.h"  
#include "base/commandlineflags.h"  
#include "foo/public/bar.h"


2. When including the header file, you should add the folder name of the project where the header file is located. That is, if you have such a project base and there is a logging.h in it, then External inclusion of this header file should be written like this:

#include "base/logging.h" instead of #include "logging.h"

What we see here is "Google C++ Programming The hidden purpose behind the principles advocated by "Style Guide" is:


#1. In order to reduce hidden dependencies and match the header file with its implementation file, its preferences should be included first ( That is, its corresponding header file).

2. Except for the preferences, the principle is from general to specific. However, I think the order of the "Google C++ Programming Style Guide": C standard library, C++ standard library, header files of other libraries, and header files of your own project misses the first item: operating system level header files, such as The above example sys/types.h probably cannot be classified into the C standard library, but is the SDK provided by the Linux operating system. Therefore, I think a more accurate statement should be: OS SDK .h, C standard library, C++ standard library, header files of other libraries, and header files of your own project.


#3. The reason why the project directory where the header file is located should be listed is because the namespaces are the same, in order to distinguish the duplicate file names caused by accident.

two. Different viewpoints in "C++ Programming Thoughts"

Different from the "Google C++ Programming Style Guide", "C++ Programming Thoughts" advocates a different rule. "C++ Programming Thoughts" P432 mentioned:

The order in which header files are included is from "the most specific to the most general". That is, any header files in the local directory are included first. Then come all our own "tool" headers, followed by third-party library headers, followed by standard C++ library headers and C library headers.

To understand the reason: You can read JohnLakos' passage in "Large Scale C++ Softwre Design" (Note: Its Chinese translation is "Large Scale C++ Programming"):

Guarantee.h The components of the file are not parsed by themselves, which avoids potential usage errors. Because being parsed by itself lacks an explicitly provided declaration or definition. Including the .h file in the first line of the .c file ensures that all internal information blocks important to the physical interface of the component are in the .h (if some information blocks are indeed missing, they can be compiled once the .c file is Found this problem).

If the order of including header files is "from most specific to most general", if our header file is not parsed by itself. We'll find it right away and prevent trouble from happening.

three. My experiment


#Which inclusion order is better? I used VS 2005 to compile a console test project TestInc, which contains several files.


The code of MyMath.h is as follows:

#pragma once  
double acos(double Num);
MyMath.cpp的代码如下:
double acos(double Num)  
{  
    return 1.0;  
}


The code of TestInc.cpp is as follows:

#include "TestInc.h"  
#include <stdio.h>  
#include <math.h>  
  
int _tmain(int argc, _TCHAR* argv[])  
{  
    double a = acos(0.5);  
    return 0;  
}

The result was an error:

1>c:program filesmicrosoft visualstudio 8vcincludemath.h(107) : error C2732: 链接规范与“acos”的早期规范冲突
1>       c:program filesmicrosoft visual studio 8vcincludemath.h(107) : 参见“acos”的声明


Then I changed the inclusion sequence of the header file of TestInc.cpp to:

#include <stdio.h>  
#include <math.h>  
#include "TestInc.h"

The compilation passed. When debugging and running, the main function call is still the function acos of the C standard library. It seems that the order of function calls is based on the order of inclusion of the header file, that is, my custom acos function is overwritten (if TestInc.h contains If the function is connected, the inline function will be called first).


From this small experiment, I came to the following conclusion: The order of including header files advocated by "Google C++ Programming Style Guide" and "C++ Programming Thoughts" each has its own advantages. "Google C++ Programming Style Guide" should be able to significantly reduce hidden header file dependencies, while "C++ Programming Ideas" will easily let you know whether the interface you define conflicts with system libraries and third-party libraries.


Four. Precompilation function in header file inclusion


When developing in the Visual Studio environment, we found that almost every cpp file must include the stdafx.h file, and it must be placed in the frontmost position, otherwise an error will occur. Why is this?

原来Visual Studio采用一种预编译的机制。要了解预编译机制,先介绍一下预编译头。所谓的预编译头就是把一个工程中的那一部分代码,预先编译好放在一个文件里(通常是以.pch为扩展名的),这个文件就称为预编译头文件这些预先编译好的代码可以是任何的C/C++代码,甚至是inline的函数,但是必须是稳定的,在工程开发的过程中不会被经常改变。如果这些代码被修改,则需要重新编译生成预编译头文件。注意生成预编译头文件是很耗时间的。同时你得注意预编译头文件通常很大,通常有6- 7M大。注意及时清理那些没有用的预编译头文件。


也许你会问:现在的编译器都有Time stamp的功能,编译器在编译整个工程的时候,它只会编译那些经过修改的文件,而不会去编译那些从上次编译过,到现在没有被修改过的文件。那么为什么还要预编译头文件呢?答案在这里,我们知道编译器是以文件为单位编译的,一个文件经过修改后,会重新编译整个文件,当然在这个文件里包含的所有头文件中的东西(.eg Macro, Preprocessor )都要重新处理一遍。 VC的预编译头文件保存的正是这部分信息。以避免每次都要重新处理这些头文件。

根据上文介绍,预编译头文件的作用当然就是提高便宜速度了,有了它你没有必要每次都编译那些不需要经常改变的代码。编译性能当然就提高了。

要使用预编译头,我们必须指定一个头文件,这个头文件包含我们不会经常改变的代码和其他的头文件,然后我们用这个头文件来生成一个预编译头文件(.pch 文件)想必大家都知道StdAfx.h这个文件。很多人都认为这是VC提供的一个“系统级别”的,编译器带的一个头文件。其实不是的,这个文件可以是任何名字的。我们来考察一个典型的由AppWizard生成的MFC Dialog Based 程序的预编译头文件。(因为AppWizard会为我们指定好如何使用预编译头文件,默认的是StdAfx.h,这是VC起的名字)。我们会发现这个头文件里包含了以下的头文件:

#include <afxext.h> // MFC extensions  
#include <afxdisp.h> // MFC Automation classes  
#include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls 
#include <afxcmn.h>


这些正是使用MFC的必须包含的头文件,当然我们不太可能在我们的工程中修改这些头文件的,所以说他们是稳定的。


那么我们如何指定它来生成预编译头文件。我们知道一个头文件是不能编译的。所以我们还需要一个cpp文件来生成.pch 文件。这个文件默认的就是StdAfx.cpp。在这个文件里只有一句代码就是:#include“Stdafx.h”。原因是理所当然的,我们仅仅是要它能够编译而已―――也就是说,要的只是它的.cpp的扩展名。我们可以用/Yc编译开关来指定StdAfx.cpp来生成一个.pch文件,通过/Fp 编译开关来指定生成的pch文件的名字。打开project ->Setting->C/C++ 对话框。把Category指向Precompiled Header。在左边的树形视图里选择整个工程,Project Options(右下角的那个白的地方)可以看到 /Fp “debug/PCH.pch”,这就是指定生成的.pch文件的名字,默认的通常是 .pch。然后,在左边的树形视图里选择 StdAfx.cpp,这时原来的Project Option变成了 Source File Option(原来是工程,现在是一个文件,当然变了)。在这里我们可以看到 /Yc开关,/Yc的作用就是指定这个文件来创建一个Pch文件。/Yc后面的文件名是那个包含了稳定代码的头文件,一个工程里只能有一个文件的可以有 YC开关。VC就根据这个选项把 StdAfx.cpp编译成一个Obj文件和一个PCH文件。


这样,我们就设置好了预编译头文件。也就是说,我们可以使用预编译头功能了。以下是注意事项:


1)如果使用了/Yu,就是说使用了预编译,我们在每个.cpp文件的最开头,包含你指定产生pch文件的.h文件(默认是stdafx.h)不然就会有问题。如果你没有包含这个文件,就告诉你Unexpected file end.

2)如果你把pch文件不小心丢了,根据以上的分析,你只要让编译器生成一个pch文件就可以了。也就是说把stdafx.cpp(即指定/Yc的那个cpp文件)重新编译一遍就可以了。


那么在Linux平台下有没有这种预编译机制呢?如果有,它是怎么实现的呢?Linux平台下GCC编译器也实现了预编译机制的。这里以开源IDE CodeBlocks(CodeBlocks内置了GCC编译器)的工程为例来说明Linux平台的实现:

使用CodeBlocks建一个C++工程,然后新建一个my_pch.h,输入如下代码:

/*************************************************************** 
 * Name:      my_pch.h 
 * Purpose:   Header to create Pre-Compiled Header (PCH) 
 * Author:     () 
 * Created:   2010-10-26 
 * Copyright:  () 
 * License: 
 * 使用方法: 项目构建选项-->其他选项-->填入下面两行 
 -Winvalid-pch 
 -include my_pch.h 
 **************************************************************/  
  
#ifndef MY_PCH_H_INCLUDED  
#define MY_PCH_H_INCLUDED  
  
// put here all your rarely-changing header files  
  
#include <iostream>  
#include <string>  
  
#endif


然后在项目构建选项–>其他选项–>填入下面两行

-Winvalid-pch
-include my_pch.h

就可以启用预编译文件头。


然后 main.cpp 就可以不用 include 头文件了,直接这样就可以编译了

int main()  
{   
using namespace std;  
    cout << "Hello world!" << endl;  
    return 0;  
}


即使在上面的代码写上下面一行,其实是不起作用的:

#include <iostream>

以上就是C++ 头文件的包含顺序研究的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn