How do I make header files?

I have gotten to a point in my course where they use CodeBlocks to automatically make a header file. However, I don’t think it’s necessary to download CodeBlocks specifically for this reason, and so I am looking for a way to make my own header files, without any fancy way to do it.

And so, I started my search online to find out exactly how to do this. But 45 minutes later, I was even more confused than I started.

First off, is making a header file really as easy as just sticking a .h or .hpp to the end of it?

Second, cplusplus.com uses #ifndef __X_H_INCLUDED__ and #define __X_H_INCLUDED__, with 2 underscores surrounding the #ifndef and #define, whereas Stack Answers use #ifndef YOUR_NAME_INCLUDE and #define YOUR_NAME_INCLUDE which don’t include the underscores mentioned.

Third, what I should put in the “ifndef” and “define” parts?

If I have a file foo.h, which looks like this:

#ifndef ???
#define ???

int sum(int a, int b) {
    return a + b;
}

#endif

should I put SUM_INCLUDED, FOO_INCLUDED, FOO_H instead of the ??? or something else altogether?

Please do not mark this as duplicate, as I don’t want to search much longer.

Answer

 #ifndef FOO
 #define FOO

 struct foo {};

 #endif

The above canonical example ensures that the contents (between #ifndef FOO and #define FOO) are compiled only once allowing us to include this file (say foo.h) in multiple compilation units without causing struct foo to be multiply defined.

There really isn’t any “magic” about an include file other than this. In fact, the extension doesn’t even matter. It could be foo.h or foo.hh or just foo (like the standard library headers like vector or iostream).

Ultimately, it’s personal preference how you structure your include guards. Some use __FOO__ (note this runs afoul of C++ standard regarding reserved identifiers) or FOO_H_INCLUDED (which is standard compliant) while others may elect for different patterns.

While it’s not strictly standard C++, my team uses #pragma once and foregoes the ifndef/define/endif code. It’s supported by all the compilers we use (gcc/msvc/clang) and you don’t have drawbacks such as too different foo.h files causing one (or the other) definition to be excluded.

The same file then looks like this

#pragma once
struct foo {};

Leave a Reply

Your email address will not be published. Required fields are marked *