1

Does C compiler cache a header file and parse it only once if the file starts with a comment?

// Some comment
#ifndef HEADER_GUARD
#define HEADER_GUARD

#endif

The question is about compilers, that can cache headers to not parse them more than once.

MD XF
  • 7,062
  • 7
  • 34
  • 64
  • 4
    This is implementation dependent. The compiler may or may not cache this information. Some ocmpilers have the `#pragma once` that may be more efficient than header guards. Aso read this: https://stackoverflow.com/questions/1143936/pragma-once-vs-include-guards – Jabberwocky Nov 23 '17 at 08:16

1 Answers1

9

Yes, this optimization is done. gcc documents it quite explicitly here: https://gcc.gnu.org/onlinedocs/cppinternals/Guard-Macros.html

Basically, if you have a well-written include guard, gcc won't touch the header twice. And a comment outside of the include guard does not stop the optimization (it would be worthless otherwise with all the license comments that precede virtually all open-source header files).

cmaster - reinstate monica
  • 33,875
  • 7
  • 50
  • 100