z32a7ul
z32a7ul

Reputation: 3777

C++ alias for global namespace

I use Visual Studio to create programs in C++ for Windows. I wonder what the best method is to write Windows API functions (including macros) as if they were part of a namespace, e.g. WinAPI. I used to define a macro that is empty, so the preprocessor deletes it, and only the :: will stay in the code, which means global scope:

#define WinAPI
BOOL bResult = WinAPI::SetWindowText( hwnd, L"Test Text" );

// After preprocessing:
BOOL bResult = ::SetWindowText( hwnd, L"Test Text" );

However, I ran into problems with macros, like ListBox_AddString; moreover I don't think that my solution was neat.

I would like to see at first glance whether a function call is part of Windows API, or one of my functions with a similar name. Is there a solution which uses namespaces somehow instead of an empty macro?

Update

I tried to implement Richard Hodges' proposal (using Visual Studio 2010):

namespace MyNamespace
{
    int APIENTRY wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR szCmdLine, int iShowCmd )
//...
}

First I received LNK1561: entry point must be defined, so I set Project Properties > Linker > Linker > Advanced > Entry Point = MyNamespace::wWinMain

Then I received LNK1221: a subsystem can't be inferred and must be defined, so I set Project Properties > Linker > Linker > System > SubSystem = Windows (/SUBSYSTEM:WINDOWS)

Now it compiles, links and runs, but iShowCmd is 0x7efde000 (a value I cannot interpret) instead of the usual (SW_SHOW = 0x00000001).

What is wrong?

Upvotes: 1

Views: 509

Answers (1)

Richard Hodges
Richard Hodges

Reputation: 69882

I think you'll find that it's more productive to put all your application's classes and functions in an app namespace, and treat the global namespace as belonging to the 'current system environment'.

The global namespace is always already polluted with c libraries, windows, posix, OSX, etc.

You can't avoid that, since there are no operating systems with only a c++ API.

Upvotes: 6

Related Questions