Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should the include guards be unique even between namespaces?

I am using same class name in two namespaces, say A and B. Should the include guards be unique while declaring the classes with different namespaces too?

I mean can't there be two files names AFile.h (in different directories) with same include guards and declaring different namespaces?

 //File 1:

 #ifndef AFILE_H 

 #define AFILE_H

 namespace A { 

   class CAFile {...

   }; 

 };

 #endif

//File 2:

 #ifndef AFILE_H 

 #define AFILE_H

 namespace B { 

   class CAFile {...

   }; 

 };

 #endif
like image 495
Sulla Avatar asked Jul 19 '26 00:07

Sulla


2 Answers

Your guards need to be different if some code (directly or indirectly) needs to see both A::CAFile and B::CAfile.

The include guards are dealt with by the preprocessor, that has no knowledge at all of classes (let alone namespaces). If both these files are included when processing a c++ file, and they have the same header guards, only one of the declarations will remain in the preprocessed source that the compiler will see.

Look at things like Boost files, they have some conventions for the header guards (if I remember correctly).

like image 142
Mat Avatar answered Jul 20 '26 16:07

Mat


Include guards only affect the preprocessor and the preprocessor doesn't know C++ and completely ignores namespaces. So guards should be unique to a file, not to a namespace.

like image 42
sharptooth Avatar answered Jul 20 '26 16:07

sharptooth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!