Not registered yet?
Register now! It is easy and done in 1 minute and gives you access to special discounts and much more!
By Asad Khan
I have been seeing code like this usually in the start of header files:
And at the end of the file is
What is the purpose of this?
This prevent from the multiple inclusion of same header file multiple time.
//header file content
Suppose you have included this header file in multiple files. So first time
__COMMON_H__ is not defined, it will get defined and header file included.
Next time __COMMON_H__ is defined, so it will not include again.
Those are called #include guards.
Once the header is included, it checks if a unique value (in this case HEADERFILE_H) is defined. Then if it's not defined, it defines it and continues to the rest of the page.
When the code is included again, the first ifndef fails, resulting in a blank file.
That prevents double declaration of any identifiers such as types, enums and static variables.
Koning Baard XIV: VC even has a #pragma once which does the same :-)
Also it prevents recursive inclusions... Imagine "alice.h" includes "bob.h" and "bob.h" includes "alice.h" and they don't have include guards...
@Kevin: that is what I mean. I wanted to manipulate a form which was opened by the form to manipulate. It gaveme lots of errors and I didn't know what to do. I gave up =)
@Јοеу: #pragma once is not portable; the common #ifndef idiom is recommended.
What is the problem of including headers multiple times? assuming no recursive inclusion... Is it a problem of same name variables, or maybe just a problem of a larger exe file?
/* code */
/* code to include if the token is defined */
#ifndef checks whether the given token has been #defined earlier in the file or in an included file; if not, it includes the code between it and the closing #else or, if no #else is present, #endif statement. #ifndef is often used to make header files idempotent by defining a token once the file has been included and checking that the token was not set at the top of that file.
Identifiers starting with an underscore are reserved; you shouldn't define them yourself. Use something like #ifndef H_HEADER_NAME.
I know this is an old comment, but actually the underscore restriction only applies to "external identifiers" - identifiers that could end up in the compiled object's symbol table, i.e. global variables and function names. It does not apply to macro names.
Is Stu's comment true? I just read stackoverflow.com/questions/228783/… and now I am not so sure.