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

后端 未结 8 1319
一向
一向 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:38

    #undef CreateDirectory

    0 讨论(0)
  • You can take a back up of CreateDirectory, then undefine it, and then define it again when you finish your job with you custom one.

    #ifdef CreateDirectory
    #define CreateDirectory_Backup CreateDirectory
    #undef CreateDirectory
    #endif
    
    // ...
    // Define and use your own CreateDirectory() here.
    // ...
    
    #ifdef CreateDirectory_Backup
    #define CreateDirectory CreateDirectory_Backup
    #undef CreateDirectory_Backup
    #endif
    
    0 讨论(0)
  • 2020-12-10 11:38
    #pragma push_macro("CreateDirectory")
    

    If nothing works, instead of renaming you could use your own namespace for your functions.

    0 讨论(0)
  • 2020-12-10 11:41

    You could create a module whose sole purpose is to #include <windows.h> and look up CSIDL_LOCAL_APPDATA wrapped in a function.

    int get_CSIDL_LOCAL_APPDATA(void)
    {
        return CSIDL_LOCAL_APPDATA;
    }
    

    btw, Well done for working out what happened!

    0 讨论(0)
  • 2020-12-10 11:42

    You will be better off if you just rename your CreateDirectory method. If you need to use windows APIs, fighting with Windows.h is a losing battle.

    Incidently, if you were consistent in including windows.h, this will still be compiling. (although you might have problems in other places).

    0 讨论(0)
  • 2020-12-10 11:52

    Note that name conflict usually comes from a certain header file being included. Until then stuff like CreateDirectory and GetMessage isn't pulled into visibility and code compiles without a problem.

    You can isolate such an inclusion into a wrapper header file and "#undef whatever" at its end. Then, whatever name collision you have will be gone. Unless, of course, you need to use those macros in your own code (yeah, so very likely...)

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