开发者

Header should be included once

开发者 https://www.devze.com 2023-03-08 02:04 出处:网络
In header files I\'ve seen two main ways for defining macro to avoid including the file mo开发者_如何学编程re than once.

In header files I've seen two main ways for defining macro to avoid including the file mo开发者_如何学编程re than once.

1.

#ifndef SOME_CLASS
#define SOME_CLASS
//code ...
#endif

2.

#ifndef SOME_CLASS
//code...
#define SOME_CLASS
#endif

Which is more preferable and why?


I prefer the first method, because it doesn't matter what happens after the ifndef because it will be defined straight after.


The first option is commonly optimized by compilers to behave like the non-standard #pragma once.

It is also safer in case of recursive includes. If, in the //code... part, you include another header which includes .... which includes the header you're currently editing, then the second version won't work.


I'd go for the first one.

Reason: If you ever want to change the guard name (say, SOME_CLASS to SOMECLASS), you don't have to scroll all the way down to the end of file to change it too.


The best option is to use #pragma once. With #define you must be very careful when using multiple libraries as the guard name may not be unique.


I prefer the first option. Suppose you include more files, and these files in turn include the file containing #ifndef SOME_CLASS.

I think it's fairly easy to spot include errors, if the #define SOME_CLASS isn't adjacent to #ifndef SOME_CLASS.

// SomeClass.h
#ifndef SOME_CLASS
#include "OtherFile.h" // will eventually lead to #include "SomeClass.h"
#define SOME_CLASS

... boat load of code here...

#endif // SOME_CLASS
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号