I am wondering why C++ compilers don't generate header guards automatically for headers?
// Why do I have to write this for every .hpp file I create?!!
#ifndef myheader_hpp__
#define myheader_hpp__
// ...
#endif
I haven't met a situation where they aren't needed when I write my headers. I can't see a real use-case of the opposite behavior, but I would be glad to see one. Is there a technical difficulty or is it just history?!
There are some preprocessor tricks that require the same header included multiple times into the same compilation unit. Another reference.
Besides that, most compilers do allow you to shorten all of that down to:
#pragma once
To a compiler, automatically putting in include guards isn't truly practical. You can define prototypes for methods/functions/classes/etc without running into problems, and this is usually done in a header. When a class is defined in a header, though, you run into the problem of having the class defined more than once by the compiler if it is included by two different .cpp files or other headers.
Really, include guards are just one trick for headers. You don't always need them, and there are some cases where you wouldn't use them. This is actually easier, believe it or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With