Search code examples
c++windowswinapiwin32ole

C++ RPC undeclared identifier and syntax errors in DLL but works in EXE


I’m developing a C++ application that uses the RPC API, and I'm encountering several errors when building a DLL. Interestingly, the same code works perfectly fine in an executable (EXE), but when I try to compile it as a DLL, I get the following errors:

Errors:

  1. C2065: 'RPC_WSTR' undeclared identifier

  2. C2146: syntax error: missing ';' before identifier 'rStatus'

  3. C2146: syntax error: missing ';' before identifier 'binding'

  4. C2143: syntax error: missing ';' before string

  5. C2059: syntax error: ')' ... and too many other errors

enter image description here

#include <Windows.h>
#include <rpcdce.h>
#include <rpcndr.h>
#include <iostream>

#pragma comment(lib, "Rpcrt4.lib")

int ConnectToRPC() {
    RPC_STATUS rStatus;
    RPC_WSTR binding;

    // RPC function to create a binding handle
    rStatus = RpcStringBindingComposeW(nullptr, (RPC_WSTR)L"ncalrpc", nullptr, (RPC_WSTR)L"ncalrpc:[ServiceEndPoint]", nullptr, &binding);
    if (rStatus != RPC_S_OK) {
        printf("failed to create a binding handle \n");
        return -1;
    }
    return 0;
}

BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
    switch (ul_reason_for_call) {
    case DLL_PROCESS_ATTACH:
        ConnectToRPC();
        break;
    case DLL_THREAD_ATTACH:
        break;
    case DLL_THREAD_DETACH:
        break;
    case DLL_PROCESS_DETACH:
        break;
    }

    return TRUE;
}

What I’ve tried:

  • The code works perfectly when compiled as a regular EXE.
  • I’m using the correct headers (<rpcdce.h>, <rpcndr.h>) and linking against Rpcrt4.lib in both the EXE and DLL projects.
  • I’ve confirmed that the rStatus and binding variables are correctly declared, but the errors persist in the DLL build. I’ve ensured that the DLL is being built with the correct configurations and dependencies.

Solution

  • C2146: syntax error: missing ';' before identifier 'rStatus'

    This is because the compiler doesn't know what RPC_STATUS is. Subsequent errors are just side-effects of your rStatus variable being incomplete.

    RPC_STATUS is declared in rpc.h. You should #include ONLY that file, not #include either rpcdce.h or rpcndr.h directly.

    The code works perfectly when compiled as a regular EXE.

    Because by default, windows.h uses #include <rpc.h> on a Windows build if WIN32_LEAN_AND_MEAN is not defined.

    I'm using the correct headers (<rpcdce.h>, <rpcndr.h>)

    But not rpc.h, which is the main header for the whole RPC API.