C++ Header order [closed]

2019-01-05 10:12发布

What order should headers be declared in a header / cpp file? Obviously those that are required by subsequent headers should be earlier and class specific headers should be in cpp scope not header scope, but is there a set order convention / best practice?

10条回答
我只想做你的唯一
2楼-- · 2019-01-05 10:51

It's a dependency thing and it depends largely on what you put in our headers. A fact is that you can be really notorious about this and minimize to keep your includes strict but you'll eventually run into a scenario where you'll wanna use inclusion guards.

#ifndef MY_HEADER_H
#define MY_HEADER_H
//...
#endif

The problem isn't that apparent in the beginning, but as the complexity of your software grows so does your dependencies. You can do well, and be smart about it but larger C++ projects are generally riddled with includes. You can try, but you can only do so much. So be diligent and think about your includes, YES! But you'll most certainly have cyclic dependencies at some point and that is why you need inclusion guards.

查看更多
别忘想泡老子
3楼-- · 2019-01-05 10:52

I used to order them in alphabetical order (easier to find)

查看更多
趁早两清
4楼-- · 2019-01-05 10:54

The "how" is not obvious, but the "what" is. Your goal is to make sure that the order in which you include header files never matters (and i mean "NEVER !").

A good help is to test whether header files compile when building cpp files (one for each header file) that only include one of them.

查看更多
\"骚年 ilove
5楼-- · 2019-01-05 10:54

I've found the following convention the most useful:

module.cpp:

// this is the header used to trigger inclusion of precompiled headers
#include <precompiled.h> 
// this ensures that anything that includes "module.h" works
#include "module.h"
// other headers, usually system headers, the project

The important thing is to put the module's header as the first non-precompiled header. This ensures "module.h" has no unexpected dependencies.

If you're working on a large project with slow disk access times, I've seen this style used to decrease build times:

module.cpp:

// this is the header used to trigger inclusion of precompiled headers
#include <precompiled.h> 
// this ensures that anything that includes "module.h" works
#include "module.h"
// other headers, usually system headers, the project
#if !defined _OTHER_MODULE_GUARD_
#include "other_module.h"
#endif 

#if !defined _ANOTHER_MODULE_GUARD_
#include "another_module.h"
#endif 

It's a bit verbose but does save on disk seeking since the header won't be searched for / opened if it's already been included. Without the guard check, the compiler will seek for and open the header file, parse the whole file to end up #ifdefing the whole file out.

查看更多
登录 后发表回答