title: LoadLibraryExA: The loaded DLL uses another DLL, which seems to use LoadLibrary and fails
body: <p>I am writing a small programming language interpreter on Windows 7. It has an &quot;extension module&quot; mechanism, triggered when the programmer says <code>import something</code>.</p>
  <p>And &quot;extension module&quot; is a DLL (in this case <code>something.dll</code>). It is loaded by the interpreter using <code>LoadLibraryExA</code>.</p>
  <p>The DLL may be dynamically linked to other DLLs (by load-time linking, <em>not</em> using <code>LoadLibrary</code>).</p>
  <p>I'm loading the extension module this way:</p>
  <pre><code>HMODULE handle = LoadLibraryExA(path, NULL, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR);
  </code></pre>
  <p>Generally this works :) I simply place any DLL that the extension module uses, in the same directory as the extension module.</p>
  <p>The problem seems to arise, when a dependency of the extension module tries to use <code>LoadLibrary</code> to load another DLL during runtime.</p>
  <p><strong>My concrete issue:</strong></p>
  <p>I have written an extension module which is a wrapper around the <code>SDL2.dll</code> and <code>SDL2_image.dll</code> libraries.</p>
  <p>Internally, <code>SDL2_image.dll</code> apparently uses something like <code>LoadLibrary</code> to load <code>libpng16-16.dll</code>. It does so when the extension module calls <code>IMG_Init()</code>. <code>IMG_Init()</code> fails, and <code>IMG_GetError()</code> returns this string:</p>
  <pre><code>Failed loading libpng16-16.dll: The specified module could not be found.
  </code></pre>
  <p>This is the directory structure:</p>
  <pre><code>interpreter.exe (the main executable, started from a CWD somewhere else in the computer)
     /stdlib
        (Loaded by the executable using LoadLibraryExA)
        extension_module.dll
      
        (Loaded for extension_module.dll by the OS directly during load time)
        SDL2.dll
        SDL2_image.dll
  
        (Trying to be loaded dynamically by SDL2_image.dll during runtime)
        libpng16-16.dll
        zlib1.dll
  </code></pre>
  <p>As mentioned, <code>extension_module.dll</code> is loaded successfully along with its dependencies <code>SDL2.dll</code> and <code>SDL2_image.dll</code>. The failure occurs when <code>extension_module.dll</code> tries to call <code>IMG_Init()</code> on <code>SDL2_image.dll</code>.</p>
  <p>This is fixed when I add the full path to the <code>stdlib</code> directory to the <code>PATH</code>.</p>
  <p>However: I would like to be able to simply execute <code>interpreter.exe</code> from anywhere in the computer, and have everything work.</p>
  <p>I desire a &quot;self contained&quot; solution - where the only thing I need to do for an extension module, is to put it and all of its recursive dependencies in the <code>stdlib</code> directory.</p>
  <p>How can I achieve this?</p>