Is it safe to wrap windows header file in a namespace?

Viewed 115

The following code can compile

#include <type_traits>
#include <iostream>
namespace win32 {
    extern "C" {
        #include <windows.h>
    }
}
int main()
{
    char buf[MAX_PATH]{};
    win32::GetModuleFileNameA(nullptr, buf, std::extent_v<decltype(buf)> - 1);
    std::cout << buf;

    return 0;
}

But I'm not confident if it is safe to wrap windows header files in this way. Can I always do this on windows programming?

1 Answers

No.

The Windows header is not designed to be encapsulated in any way.

Unless you are writing a Win32 application that uses the Windows API extensively for its basic function, you should limit its use to source code separated from the rest of your program’s source code. For example:

platform.hpp

#include <string>

namespace platform
{
  std::string GetExeFileName();
}

platform.cpp

#include "platform.hpp"
#include <windows.h>

std:string platform::GetExeFileName()
{
  char buf[MAX_PATH];
  DWORD ok = GetModuleFileNameA( NULL, buf, MAX_PATH );
  return ok ? buf : "";
}

main.cpp

#include <iostream>
#include <string>
#include "platform.hpp"

int main()
{
  std::cout << platform::GetExeFileName() << "\n";
}
Related