cgmb / guardonce

Utilities for converting from C/C++ include guards to #pragma once and back again.
MIT License
142 stars 3 forks source link

Using include guards and pragma once together #17

Open cgmb opened 7 years ago

cgmb commented 7 years ago

It seems a lot of people like the idea of using both include guards and #pragma once in the same file. I'm not a fan.

\

Unlike just using #pragma once, if you use both together you still need to manually maintain the uniqueness of the include guard symbol. Eliminating that burden was the best feature of #pragma once, in my opinion. With that gone, the only possible advantage of also using #pragma once would be performance, but there is no performance improvement on modern compilers.

Compilers can recognize that a file is protected by include guards and optimize its inclusion just as they would for #pragma once (as long as they check that the guard is never #undef'd). GCC has long done this, but MSVC historically lacked this optimization. That's the main reason why you see so much old information promoting the use of #pragma once and include guards together.

That information is out of date. To quote Microsoft's documentation on #pragma once in VS2015:

There is no advantage to use of both the #include guard idiom and #pragma once in the same file. The compiler recognizes the #include guard idiom and implements the multiple include optimization the same way as the #pragma once directive if no non-comment code or preprocessor directive comes before or after the standard form of the idiom:

\

With all that being said, it's clear that using both together is a style that many people use. guardonce has no support for working with files that contain both, but maybe it should. At the very least, it should help people migrate away from using both to using just one.

brdjns commented 1 year ago

Ironically the very same Microsoft are themselves guilty of committing the same sin.