views:

134

answers:

2

Hi Can we write a portable include guard that doesn’t use the preprocessor in c++ ?? If so how could that be done ?

+1  A: 

That's a bit of a non-starter. If you're #including files you are stuck using the preprocessor, regardless. The closest thing you to what you ask that I'm aware of is the #pragma once preprocessor directive, but that's not strictly portable - although it is widely available - and it of course relies on the preprocessor.

Void
+6  A: 

No.

  1. You cannot use #include without the preprocessor.
  2. Without preprocessor directives, including the same file twice will always result in the same sequence of tokens.

There are a couple non-portable ways to do this (both use the preprocessor), such as:

#pragma once

and

#import "file.h"

But header guards work everywhere, and your compiler is probably optimized to check for header guards so it won't even bother processing a duplicate #include directive.

Dietrich Epp
+1 Agreed. GCC is one compiler that performs the include guard check.
Void