Loading DLL with alternate search path not looking at current directory for dependent DLL

BlueBird 1 Reputation point

To load DLL dynamically (for desktop application using C++), I use


The reason I use alternate search path is to load the dependent dlls from the Dll directory instead of the application directory (giving higher priority to the DLL dir). But I call SetCurrentDirectory as a fallback search option so that if the dependent DLL cannot be found from the dll directory, then it can search the application directory which is set to be the current directory.

For example, say, I have foo.dll (<pathfoo>/foo.dll) which is dependent on bar.dll. Let's say bar.dll is not existing in <pathfoo> but it is existing in my <appdir>, then it is able to load bar.dll from the current dir (<appdir>) after its first search failed to load from <pathfoo>.

This flow has worked perfectly for a long time. But recently after a 3rd-party DLL update, it fails to locate the dependent DLL from the current directory. I exactly don't know what the 3rd-party DLL is doing. But I was able to replicate the behavior by linking a dummy DLL that executes the following function:


After this call, current directory is no longer searched. From the msdn documentation, it is not very clear what happens to alternate search after setting LOAD_LIBRARY_SEARCH_USER_DIRS. But if I call SetDefaultDllDirectories with LOAD_LIBRARY_SEARCH_DEFAULT_DIRS right before my LoadLibraryEx call, then the working directory is searched. This is really mysterious - doc doesn't say anything about this.

So now I have two solutions before calling LoadLibraryEx:

a) call SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS) -- which I don't know how it works. So I'm not confident in using this.
b) add <appdir> to on top of the %PATH% environment variable -- it seems an ugly workaround.

Could anybody explain why the current directory is not searched, and suggest a better workaround? Thanks.

Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,062 questions
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
2,889 questions
{count} votes