I am using the <conio.h>
header file, and somewhere else in my source code I define a function with the name getch
and it has to have that name. Since there already is a getch
in <conio.h>
, and this header file declares all of its functions in the global namespace, I get a name collision.
I found that using the following syntax would avoid the collision:
namespace some_namespace
{
#include <conio.h>
}
Then I can use some_namespace::getch
when I want to access the function in <conio.h>
and getch
when I want to access my own function.
Is this valid syntax? I know <conio.h>
is only for windows, but is this kind of syntax going to behave the same across all the compilers? What other ways do you suggest to get around this problem?
I use GCC and MSVC 2019 on Windows and it compiles fine on both of them.
I can access the functions in <conio.h>
as well, getch
in particular as I showed above (even though I should use the name _getch
instead of getch
in MSVC).
System header files like <conio.h>
which are intended to be used in both C and C++ will enclose their declarations in an extern C
scope, forcing C linkage for all that is contained in them, regardless of whatever additional C++ namespaces you add. That’s why your code compiles in this case.
See also this, which is almost a duplicate of this question, but not exactly.
In short, yes it’s valid, but I would strongly encourage against it. There are many other ways to solve this problem, like creating wrapper modules for the functions you want to have alternate symbols for.
As a side note: try putting your own getch
in an extern C
block. My guess is you’ll get a linker error.