Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have you ever written a header without guards?

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?!

like image 715
Khaled Alshaya Avatar asked Oct 14 '11 03:10

Khaled Alshaya


2 Answers

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
like image 99
Ben Voigt Avatar answered Sep 30 '22 13:09

Ben Voigt


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.

like image 43
Thomas Havlik Avatar answered Sep 30 '22 12:09

Thomas Havlik