How do I avoid name collision with macros defined in Windows header files?

后端 未结 8 1320
一向
一向 2020-12-10 11:24

I have some C++ code that includes a method called CreateDirectory(). Previously the code only used STL and Boost, but I recently had to include

相关标签:
8条回答
  • 2020-12-10 11:53

    push macro, undef it and pop the macro again:

    #pragma push_macro("CreateDirectory")
    #undef CreateDirectory
    void MyClass::CreateDirectory()
    {
     // ...
    }
    #pragma pop_macro("CreateDirectory")
    
    0 讨论(0)
  • 2020-12-10 11:58

    As a developer working on a cross platform codebase, this is a problem. The only way to deal with it is to

    • ensure that windows.h is - on Windows builds at least - universally included. Then the CreateDirectory macro is defined in every one of your compilation units and is universally substituted with CreateDirectoryW. Precompiled headers are ideal for this

    OR, if that is an unpleasant proposition, (and it is for me)

    • isolate windows.h usage into windows specific utility files. Create files that export the basic required functionality. The header files must use data types that are compatible with, but do NOT depend on the inclusion of windows.h. The cpp implementation file must (obviously) use windows.h.

    If your utlility functions need to include project header files with conflicting symbols then the following pattern is a necessity:

    #include <windows.h>
    #ifdef CreateDirectory
    #undef CreateDirectory
    #endif
    // etc
    #include "some_class_with_CreateDirectory_method.h"
    // ...
    

    You will need to then explicitly call the non macro version of any windows api functions you have #undef'd - CreateDirectoryA or W etc.

    0 讨论(0)
提交回复
热议问题