Including Header files

Apr 22, 2010 at 6:04am
Hi all,

Is there any hierarchy while including header files, like complier provided header files(stdio.h) has to be included first and then the user defined (user.h).

Apr 22, 2010 at 6:10am
No.

EDIT: That is, unless you're doing it wrong.
Last edited on Apr 22, 2010 at 6:10am
Apr 22, 2010 at 8:30am
It is unnecessary unless your "user.h" doesn't itself includes the header files it needs.
The best way is for your "user.h" to include files it would need beforehand so it would compile without warnings (errors in C++).

Just make sure you link to the appropriate libraries (eg. libc in gcc).
Apr 22, 2010 at 11:47am
note: when you create your own header files you should always put them in an inclusion guard
so that the compiler define them only once and will be safe to include them with each other

1
2
3
4
5
6
#ifndef  YOURHEADER_H
#define YOURHEADER_H

classes ,structs ....etc

#endif 
Apr 23, 2010 at 5:31am
Thank you all...
Apr 23, 2010 at 5:39am
can someone explain why most of you prefer guards than #pragma once which most compiler does support it including GCC
Apr 23, 2010 at 5:54am
If that is the case then I might as well use #import directive (from Objective-C/C++ but supported in C/C++ by GCC).

Older compilers did not have #pragmas at all. Forget the #pragma once directive.
Hence it's an old habit hard to get rid of. And besides, I prefer my headers in this old fashioned way.
Although, #pragma once is quite useful, I don't deny that.

The above is simply my view, but the below may apply to others:

Some headers need to redefine things when they are included again. #pragma once may not be helpful here.
Take, for example, the standard <assert.h> - which needs to redefine the assert() macro whenever it gets included depending on the NDEBUG macro definition.
Last edited on Apr 23, 2010 at 5:59am
Apr 23, 2010 at 6:02am
#pragma once is nice since it lets the compiler skip the file instead of having to read the entire file to find the #endif

However, any and all #pragma stuff isn't required to be supported, so for portability, you shouldn't rely on it doing what you think it does. Compiler ABC could say "#pragma once" includes the header file only once, but Compiler XYZ could say "#pragma once" means if the file is included more than once, give an error.
Topic archived. No new replies allowed.