Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!pt.cs.cmu.edu!pt!dld From: dld@F.GP.CS.CMU.EDU (David Detlefs) Newsgroups: gnu.gcc Subject: Is "#pragma once" necessary? Message-ID: Date: 25 Jul 89 17:01:01 GMT Organization: CMU CS Department Lines: 55 I would like to make an argument that #pragma once is unnecessary, and perhaps even dangerous. First, calling "#pragma once" a "pragma" conveys the impression that it affects only efficiency, never correctness. This is not true; if foo.h contains ifdefs that depend on the state of preprocessor variables, separate includes might produce different results. A user could put a #pragma once in such a foo.h, not realizing that it would affect the semantics of his program. (Note that when I say "conveys the impression" I do not mean to say that it is written in the Ansi C standard that pragmas shall never affect the meaning of an Ansi C program, rather that the term "pragma" has been used often in other contexts with that meaning, so that programmers might expect that to be true.) An alternative, gleaned from discussion on various netnews groups: why is "#pragma once" preferable to the #ifndef convention? The standard argument is that if we use #ifndef's, we still have to open and process a file on inclusions after the first, to find out that it's body is #ifndef'd. Instead, we could modify cpp to keep a table of the files it has processed. When a file is read for the first time, cpp checks to see if it is of the form foo.h: -------------------------------------------------- * #ifndef FOO_H * #endif * -------------------------------------------------- If so, then it is associated in the table with the variable FOO_H. Each included file name is looked up in this table before the file is opened. If found, we check the the current value of the associated variable; if it is defined, we skip the include without opening and processing the file. This seems like it should be just as efficient as "#pragma once," without changing any semantics, and preserving compatibility with existing code. I stand of course eager to hear reasons I have overlooked that make "#pragma once" preferable. NOTE: this is not my idea; I just don't know who to credit it to. If the person who made the post that I read it in (perhaps in this newsgroup?) will send me mail, I will credit him/her in any subsequent discussion, because I think this is a great idea. -- Dave Detlefs Any correlation between my employer's opinion Carnegie-Mellon CS and my own is statistical rather than causal, dld@cs.cmu.edu except in those cases where I have helped to form my employer's opinion. (Null disclaimer.)