Search code examples
c++comhresult

Issue with assigning HRESULT using CoInitializeEx


I am trying to use Microsoft's tutorial here to set up a COM connection for WMI programming. I have slightly modified the example code to fit my style. My code so far is as follows:

#include <iostream>
#include <Windows.h>
#include <WbemIdl.h>

#define _WIN32_DCOM

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

HRESULT hRes;
hRes = CoInitializeEx(0, COINIT_MULTITHREADED);

if(FAILED(hRes)) 
{
    std::cout << "COM initializtion failed." << std::endl;
}

My issue appears on the assignment at:

hRes = CoInitializeEx(0, COINIT_MULTITHREADED);

I see a little red squiggly, so I check it and it says:

Error: this declaration has no storage class or type specifier

I have no idea what the issue is I haven't really done C++ in a while, so I could me just making a dumb mistake. Some Googling lead me to an SO question that said that the type was not defined because the correct header had not been included, but (please correct me if I'm wrong on this) I thought that HRESULT was defined in Windows.h.

Can anyone see an issue with this code? It is a Win32 console application and I am using Visual Studio 2015.


Solution

  • Below code has to go inside a function..

    HRESULT hRes;
    hRes = CoInitializeEx(0, COINIT_MULTITHREADED);
    
    if(FAILED(hRes)) 
    {
        std::cout << "COM initializtion failed." << std::endl;
    }
    

    You can't write code outside function. You can write declarations but not the code itself, precisely that's what error *This declaration has no storage class or type specifier* states.