Xref: utzoo comp.lang.c:23159 comp.lang.c++:5173 gnu.g++:457 Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!rutgers!tut.cis.ohio-state.edu!pacific.mps.ohio-state.edu!gem.mps.ohio-state.edu!brutus.cs.uiuc.edu!apple!well!nagle From: nagle@well.UUCP (John Nagle) Newsgroups: comp.lang.c,comp.lang.c++,gnu.g++ Subject: A solution to the multiple inclusion problem Keywords: #include c c++ Message-ID: <14240@well.UUCP> Date: 23 Oct 89 16:34:49 GMT Distribution: comp Lines: 50 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