Click here to Skip to main content
15,895,283 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
Hi guys, I had this bothersome question.

C++
#include <Windows.h>
namespace nSpace
{
	// Creates and registers the window
	class Init
	{
	private:
		BYTE CreateWindow();
	};
}


The problem with this code, is that I can't create a function called "CreateWindow" because in the global scope (that is, in one of the Windows' header files) there is a samely named function.
So can't I make it work it out a different way? Is there any solution so as to keep that name which is very convenient to me ??
Aren't supposed that namespaces and classes can encapsulate names of functions in their scope without interfering with any other and not having to resort to the parent's scope ones?
See you around.
Posted

1 solution

The problem is that CreateWindow has already been declared as a C Preprocessor macro in WinUser.h
...
#ifdef UNICODE
#define CreateWindow CreateWindowW
#else
#define CreateWindow CreateWindowA
#endif
...

and C Preprocessor macros being an old school C feature take no account of namespaces.

There are 2 ways to deal with this. Either use a different name, I use mxCreateWindow for historical reasons or get rid of the macro definition before the parser finds your function.
#undef CreateWindow

That might seem simple enough but if you also use the global namespace CreateWindowW or CreateWindowA functions by using the name CreateWindow that code could now be broken because you've take away the macro that defined part of it.
One way round this is to use
#pragma push_macro("CreateWindow")

before your code and
#pragma pop_macro("CreateWindow")

after your code but this is very Microsoft Visual C++ specific and may not even work reliably with all versions of that so consider carefully.
 
Share this answer
 
Comments
unscathed18 10-Feb-13 15:49pm    
I think I'll stick with mxCreateWindow.
Although, The #pragma push_macro and pop_macro doesn't work for me (I use Visual C++ Express 2010) Do you know why it is it?
Matthew Faithfull 10-Feb-13 16:57pm    
Don't know why, I've had issues with them when I tried to make them work as well, probably VS2008 express back then. There's some trick to it I guess but I get suspicious when I see Microsoft's own code going around the houses where they could have used the pragmas and don't. Then again in other places they do use them so who knows. Probably best to stick with renaming to avoid the clash.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900