How do I declare OutputDebugStringA without windows.h macros?

1k Views Asked by At

You know how Python has from urllib import *, but also offers from urllib import request, so you can just import that one symbol? Unfortunately C/C++ don't offer that but that's what I would like to do here: from windows.h import OutputDebugStringA, because all I need is that one function. This is for a personal project only.

I used cl.exe main.cpp /EP to preprocess and it tells me that this should work

typedef char CHAR;
typedef  const CHAR *LPCSTR, *PCSTR;
__declspec(dllimport)
void
__stdcall
OutputDebugStringA(
     LPCSTR lpOutputString
    );

But I'm still getting a linker error: main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) void __cdecl OutputDebugStringA(char const *)" (__imp_?OutputDebugStringA@@YAXPEBD@Z) referenced in ...

Why?

2

There are 2 best solutions below

4
On BEST ANSWER

The issue is that the Windows API is C based, and thus the functions that are to be called are C functions, not C++ functions.

The problem when compiled under a C++ compiler is that the function name gets mangled (due to C++ use of function overloading). Thus the function name winds up being different than the actual function name that is defined in the import library (in this case kernel32.lib). You therefore get the linker error that the function cannot be found.

The fix is to use extern "C" as a qualifier to the function, so that C++ does not mangle the function name.

However, I do not recommend this for Windows development, i.e. not including the windows.h header file. Problems such as this can be avoided by including the windows.h header file.

0
On

So the following does the trick:

extern "C" __declspec(dllimport) void __stdcall OutputDebugStringA(const char* lpOutputString);