Two libraries containing identical include guards

It could happen that two independent libraries have two header files with identical include guards.
The following example is like that; as a consequence, the second include file is blocked by the first one.

Is this ever be a real problem? Users don't always have the luxury of editing a library.
What is the usual way to handle such a situation if the user can not edit the library?

I ran into this situation with my own libraries, so I simply changed the include guard.

lib1/A.h
1
2
3
4
5
6
7
#define A_h
#include <iostream>
namespace lib1
{
	void fn();
}
#endif 


lib1/A.cpp
1
2
#include "A.h"
void lib1::fn() { std::cout << " lib1::fn "; }


lib2/A.h
1
2
3
4
5
6
7
8
#ifndef A_h
#define A_h
#include <iostream>
namespace lib2
{
	void fn();
}
#endif 


lib2/A.cpp
1
2
#include "A.h"
void lib2::fn() { std::cout << " lib2::fn "; }


main.cpp
1
2
3
4
5
6
7
8
#include "lib1/A.h"
#include "lib2/A.h"	//has identical include guard as lib1/A.h

int main()
{
	lib1::fn();
	lib2::fn();	//error: 'lib2' has not been declared (blocked by include guard)
}


Thank you.
Last edited on
The root of the problem seems to be the shitty naming scheme. Is 'A' really the best name for that that file?

So the answer to your question is yes, If the header guards are implemented in a simplistic way. Although it isn't strictly standardized, most implementations of C++ will recognize the #pragma once directive which is usually a better header guard than the standard #ifdef/#define scheme as it generates file-specific identifiers behind the scenes. However, it may not be portable.
Thanks Esslercuffi.
The "#pragma once" directive looks interesting.
Topic archived. No new replies allowed.