0

I am writing a C++ desktop app for Windows 7 and later.
I want to get the path to the AppData/Roaming folder so I use SHGetKnownFolderPath:

#include "stdafx.h"
#include <windows.h>
#include <ShlObj.h>

void hello()
{
    LPWSTR roamingPath;
    SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, NULL, &roamingPath);

PROBLEM: Build fails with identifier "SHGetKnownFolderPath" is undefined, which is strange as I think I included the right headers.


Notes:

  • Visual Studio 2015 tells me that my compile options are /Yu"stdafx.h" /GS /analyze- /W3 /Zc:wchar_t /ZI /Gm /Od /Fd"Debug\vc140.pdb" /Zc:inline /fp:precise /D "WIN32" /D "_WINDOWS" /D "_DEBUG" /D "_USRDLL" /D "_WINDLL" /D "_MBCS" /errorReport:prompt /WX- /Zc:forScope /RTC1 /Gd /Oy- /MDd /Fa"Debug\" /EHsc /nologo /Fo"Debug\" /Fp"Debug\OverlayIcon.pch".
  • Different from Error: identifier :"SHGetKnownFolderPath" is unidentified where the problem is that the asker targets more than desktop.
Community
  • 1
  • 1
Nicolas Raoul
  • 58,567
  • 58
  • 222
  • 373
  • Your [target platform macros](https://msdn.microsoft.com/en-us/library/6sehtctf.aspx) in your stdafx.h header are likely going to be important to this question, as their values indicate what features are exposed when compiling through the headers. May want to include those in your question. – WhozCraig Mar 08 '16 at 04:15
  • @WhozCraig: Added! StackOverflow syntax problem though :-/ – Nicolas Raoul Mar 08 '16 at 04:34
  • 1
    As it sits now after you updated your post it should at least compile the source. You own that stdafx.h header in your project btw. There is little sense in not just changing the values to the proper targets right there since it is included in all your translation units anyway. – WhozCraig Mar 08 '16 at 04:39

1 Answers1

1

The trick is to add these two lines in your stdafx.h file:

#define WINVER 0x0601 // Allow use of features specific to Windows 7 or later.
#define _WIN32_WINNT 0x0601

This says that the app targets Windows 7, which is important because SHGetKnownFolderPath is only available from Windows Vista, as specified in the MSDN documentation. It did not work immediately for me, I had to clean up and even restart Visual Studio.

Here are the codes for all other versions of Windows:
https://msdn.microsoft.com/en-us/library/6sehtctf.aspx

Thanks to WhozCraig for the tip!

Nicolas Raoul
  • 58,567
  • 58
  • 222
  • 373