Search code examples
c++linkerstatic-linking

How to use shell32.dll from C++ console application


What I need to do is to get ApplicationData path , I've found in Google that there is function called

HRESULT SHGetFolderPath(
  __in   HWND hwndOwner,
  __in   int nFolder,
  __in   HANDLE hToken,
  __in   DWORD dwFlags,
  __out  LPTSTR pszPath
);

But it exists in shell32.dll In C# I'd do something like

[DllImport]
static extern HRESULT SHGetFolderPath() and so on.

What do I need to do in C++ Console application, to be able to call this API? Maybe, I can use LoadLibrary()? But what is the right way to do this?

Can I somehow statically link this dll to be part of my exe? I am using Visual Studio 2010.


Solution

  • You need to #include shlobj.h and link to shell32.lib. Like this:

    #include "stdafx.h"
    #include <windows.h>
    #include <shlobj.h>
    #include <assert.h>
    #pragma comment(lib, "shell32.lib")
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        TCHAR path[MAX_PATH];
        HRESULT hr = SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, path);
        assert(SUCCEEDED(hr));
        // etc..
        return 0;
    }
    

    The #pragma comment takes care of telling the linker about it.