[edit] It seems some people are commenting and voting without reading my post. Please read it before commenting. For instance: if you think I am against including files more than once, then you are missing the point of my post.
I would like to trap sloppy programming by outputting an error when some include files are included twice.
I use #pragma once
for include files that intend to include within other include files. That works great.
I know I can do a variation of "guard macros" to accomplish this. But is there a better way? Another #pragma or a gcc compile option?
This is a sample of a guard macro:
#ifndef FILE_FOO_SEEN
#define FILE_FOO_SEEN
the entire file
#endif /* !FILE_FOO_SEEN */
This would work for me:
#ifdef FILE_FOO_SEEN
#error "FILE_FOO inappropriately included twice.
#endif /* FILE_FOO_SEEN */
#define FILE_FOO_SEEN
/* Active Code */
[edit] Note: I am not asking for why it is necessary to support including header files multiple times. That is a common case and supported with the a gcc pragma. I am asking for the case when I have specific include files that I do not want included more than once. If someone were to include them more than once, then it would be one of two actions: 1) Change the trap to a #pragma once, or 2) change the code to eliminate the dependency.
Because there is a special pragma to support multiple include, I thought someone might have good techniques to avoid this as well.
[edit] Add some of the rules we follow related to our use of header files:
Each .c file has a companion .h file with the function prototypes. You can think of this .h file as the interface to the .c file. This .h file may also contain structure definitions and enums that are consumed or returned by the functions. This .h file does not need to be included in any other .h file because other .h files do not use functions.
We do not create a companion .h file for .c files that contain main().
Sometimes structures and enums are used independently of the functions that return or consume them. For these cases the enums and structures are moved to an independent .h file. This .h file will contain a
#pragma once
because it could be included multiple times.Opaque structures are preferred.
Doxygen documentation that documents the interface is contained in the .h files. This works well because the .h file contains the complete interface to the .c file.
We make exceptions to these rules as needed, but for the most part we adhere to these rules.
Following these rules makes writing unit tests easier as the complete interface is easy to identify and understand.