The preprocessor ignores

I am migrating from Visual Studio 6 to Visual Studio 2008 and I have a component function that I am using a name with SetDefaultPrinter

.

Unfortunately there is now a window library function of SetDefaultPrinter

the same name. And the macro associated with it is preventing me from using my function.

This is my workaround, which I have to call my function:

#undef SetDefaultPrinter
    pNova->SetDefaultPrinter();
#ifdef UNICODE
#define SetDefaultPrinter  SetDefaultPrinterW
#else
#define SetDefaultPrinter  SetDefaultPrinterA
#endif // !UNICODE

      

Is there a less ugly way? And no, I have no control over this external component to change the function name.

0


a source to share


3 answers


This is why C ++ added namespaces; too bad Windows definition can't use them.

In another source module, where you DO NOT include windows.h or any other windows files, create a stub function to call the clashing function.



void MySetDefaultPrinter(CNova * pNova)
{
    pNova->SetDefaultPrinter();
}

      

+3


a source


You can use a wrapper around the outer component. This is sometimes referred to as the "Adapter" pattern .

// header file
class NovaWrapper
{
  Nova *_nova;
  public:
    void setDefaultPrinter();
};

// implementation file - this file does not include windows.h - you need to make sure it
// does not have visibility of the "bad" SetDefaultPrinter macro
void NovaWrapper::setDefaultPrinter()
{
  _nova->SetDefaultPrinter();
}

      



Now change your client code to use NovaWrapper instead of the main instance.

+1


a source


This was eventually fixed by simply changing the order of the inclusions. Apparently, the developers of this component is to understand the problem in front of me, so they are included SetDefaultPrinterA

, and SetDefaultPrinterW

in the component, which are simply aliases for SetDefaultPrinter

. So if windows.h renames this function, that's not a problem.

0


a source







All Articles