Closed cptaffe closed 10 years ago
IIRC #import directive was introduced as the extension to the language to make C compilers faster by reducing the number of files to be processed. If a header file is already #import'ed, the compiler doesn't even have to stat() the file. On the other hand my naive implementation would open the header file and parse it only to skip the entire file contents guarded by #ifdef.
Modern C compiler however knows the #ifdef guard pattern. If it finds entire file is guarded by an #ifdef, it understands that the file wouldn't have to be loaded twice. This is very effective optimization that you can make to the compiler. Usually compilers spent most time on parsing, and #ifdef guard optimization would dramatically reduce the number of tokens that the compiler would have to read.
I don't personally use #import, as the #ifdef guard is the standard-complaint way of doing it that has no performance penalty compared to #import. #import would save a few keystrokes but it's marginal. Also, I don't think the system headers don't use the #import directive.
That being said, I agree that we probably want to add #import to the C preprocessor because it's a very popular language extension. The only reason I haven't done that yet is just because I did not see any #import directives in any file when I was developing the compiler on the Linux platform.
Implemeted the feature in https://github.com/rui314/8cc/commit/96cd011a4c32bf31220ea9ec5ae5768428d30e0d
There is a cpp directive called #import implemented in both clang and gcc compilers. I noticed it was absent from your
cpp.c
file. If you are unfamiliar, the semantics are as follows:It has no real effect on dynamically linked libraries, but on statically linked libraries, it is basically a one time #include. Meaning that the current program will only ever import a file once, which removes the need for #ifndef blocks and making up #define names for every library.
Personally I find this very useful in writing C code, and much cleaner than the include guards in every header file.