A solution to the multiple inclusion problem
John Nagle
nagle at well.UUCP
Tue Oct 24 02:34:49 AEST 1989
The problem is well-known. It would be desirable if all include files
themselves included everything they needed, so that order of inclusion
was taken care of automatically. But, of course, this results in multiple
inclusion of the same files, which causes problems. A common work-around
for this problem is to use a construct like the following in each include file:
#ifndef XXX
#define XXX
...content...
#endif
This works, but on the second inclusion, the file still has to be read and
parsed, at least by the level of processing that reads "#" statements.
(Many newer compilers do "#" processing in the same pass as main compilation,
so referring to a "preprocessor" in this context is not necessarily correct.)
With widespread use of this technique within library files, some files may
be read a large number of times, mostly to be ignored. This slows compilation.
The problem is especially severe in large C++ programs, where large numbers of
header files are necessary, and nested header files are not at all uncommon.
It's been proposed that the semantics of "#include" be changed to
avoid all multiple inclusion. But this is controversial, and would require
ANSI approval.
I propose a solution via compiler optimization.
The compiler should behave as follows:
1. If, when reading an "included" file, there are
no non-comment statements before the first "#ifndef"
(if any), and no non-comment statements after the "#endif"
matching said "#ifndef", the compiler shall associate
the tag found on the "#ifndef" line with the name of the
"#include" file.
2. When processing an "#include" statement, if the file has
an associated tag as defined in 1) above, and the tag is
defined (in the sense of "#define") the file shall not be
included.
This is a completely compatible solution to the problem. Old compilers
will compile include files written with the "ifndef" convention correctly,
but slowly, and new compilers will do it faster. No standardization
action is required. Any implementor can install this now, and speed up
their product.
One could argue for a more elegant but less compatible solution, but
the political hassles aren't worth it.
John Nagle
More information about the Comp.lang.c
mailing list