One difficulty with automatic duplicate-header exclusion is that the C standard is relatively silent on the subject of what include filenames mean. For example, suppose the main file being compiled contains directives #include "f1.h"
and #include "f2.h"
, and the files found for those directives both contain #include "f3.h"
. If f1.h
and f2.h
are in different directories, but were found by searching include paths, then it would be unclear the #include
directives within those files were intended to load the same f3.h
file, or different ones.
Things get even worse if one adds in the possibilities of include files including relative paths. In some cases where header files use relative paths for nested include directives, and where one wishes avoid making any changes to supplied header files, it may be necessary to have a header file duplicated in multiple places within a project's directory structure. Even though multiple physical copies of that header file exist, they should be regarded semantically as though they are a single file.
If the #pragma once
directive allowed an identifier to follow once
, with the semantics that the compiler should skip the file if the identifier matches one from an earlier-encountered #pragma once
directive, then the semantics would be unambiguous; a compiler which could tell that an #include
directive would load the same #pragma once
-tagged file as an earlier one, it could save a little time by skipping the file without opening it again, but such detection would not be semantically important since the file would be skipped whether or not the filename was recognized as a match. I'm unaware of any compilers working that way, however. Having a compiler observe whether a file matches the pattern #ifndef someIdentifier / #define someIdentifier / #endif [for that ifndef] / nothing following
and treating such a thing as equivalent to the above #pragma once someIdentifier
if someIdentifier
remains defined, is essentially as good.
#pragma once
which tells the compiler to only include that file once.