Home > Enterprise >  What is the purpose of defining a preprocessor macro like __BASH_H__ that is only used before it
What is the purpose of defining a preprocessor macro like __BASH_H__ that is only used before it

Time:11-25

I'm reading through some open-source code at the moment, and I see the following lines of code at the top of this C header file:

#ifndef __BASH_H__
#define __BASH_H__

I don't see __BASH_H__ referenced anywhere else in the codebase, so I suspected it is used indirectly (i.e. by the shell, a C compiler, or a 3rd-party library), not by the code itself.

I Googled for "BASH_H" and I saw it used by other open-source libraries (i.e. here and here), so I'm assuming I'm directionally correct in my assumption.

However the Google results don't include any official documentation on this declaration, its purpose, its usage(s), etc. I just see 2 pages total of search results, most of which look pretty irrelevant.

I'm assuming it's somehow related to bash, but I'm mystified by the lack of official docs. Can anyone point me in the right direction?

CodePudding user response:

It’s a classic header guard: it ensures that the header is only included once. Imagine you have a file which says

#include "bash.h"
#include "bash.h"

The first #include will result in __BASH_H__ being defined. This will then result in the #ifndef in the second inclusion failing, so the “useful” contents won’t be included again.

Avoiding double declarations is useful for a number of reasons; the main one is that many elements in C can’t be declared twice, in particular structs.

(Having a single file include the a header twice is unlikely, but multiple inclusions can easily happen when headers include other headers: a.c includes b.h and c.h, and b.h includes c.h.)

There’s no external use for such guards, they are an implementation detail of the header file.

The name __BASH_H__ is chosen to have a good chance to be unique; any sufficiently distinguishable token could be used instead, idontwantbashhincludedtwice, single_bash_h, whatever. It doesn’t have a value, all that matters is whether it is defined or not. Its only use is in the pair of #ifndef/#define lines. (It’s commonly repeated as a comment alongside the matching #endif, but that doesn’t matter to the pre-processor.)

A common C compiler extension which achieves the same result is #pragma once.

  • Related