... an #include guard, sometimes called a macro guard, is a particular construct used to avoid the problem of double inclusion when dealing with the include directive. (Link)
Example:
// person.h #ifndef PERSON_H #define PERSON_H typedef struct { char* first_name; char* last_name; int age; } person; #endif /* PERSON_H*/The idea is to let the C preprocessor only evaluate the guarded code if the global symbol PERSON_H is not defined. Since line 3 defines PERSON_H as the very first step the person struct is guaranteed to be seen only once at compilation time.
It is simple macro programming but so popular that an IDE like Eclipse CDT auto-generates the include guard for you. You can even choose different naming schemes.
But this technique also has some downsides:
- three lines of extra code
- potential name clashes if there is another person.h in an included project
The latter one can be worked around with improved naming schemes like adding the path to the symbol name (#define MY_PROJECT_SRC_PERSON_H) or using a simple random number (#define DF454FSKWDLD) but stop - this hack is getting worse and worse.
Luckily there is a solution for quite some time now called #pragma once. The above example looks rewritten like this:
// person.h #pragma once typedef struct { char* first_name; char* last_name; int age; } person;The ‘#pragma’ directive is the method specified by the C standard for providing additional information to the compiler, beyond what is conveyed in the language itself. [Link].
And this is what #pragma once does:
#pragma once is a non-standard but widely supported preprocessor directive designed to cause the current source file to be included only once in a single compilation. [Link]
The Wikipedia page which provides this quote gives also a list of compilers which provide this feature. If you're not forced to compile under Solaris studio you're fine.
Keine Kommentare:
Kommentar veröffentlichen