LoadLibrary() error code 127

Adam Tegen picture Adam Tegen · Jun 27, 2009 · Viewed 39.4k times · Source

I'm having trouble with LoadLibrary() and getting an error that doesn't make sense to me:

   ::SetLastError(0);

   m_hDll = ::LoadLibrary(szName);

   if (m_hDll == NULL) // Failure to load the DLL.
   {
      DWORD err = GetLastError();
   }

The error is 127 ("The specified procedure could not be found.") That doesn't make any sense to me on a call to LoadLibrary(). I haven't called GetProcaddress() yet.

The DLL (and the application) are both compiled with VS++ 2005 SP1.

What could be going wrong?

Answer

Michael picture Michael · Apr 8, 2010

Let's take this step by step:

  1. The error message means that the dll was found but a required function is missing. (Jitter is right.) This implies that you have the dll you need, but not the right version. (Davefiddes is right, although the problem can be any dll, not just the Microsoft runtime library. And, at least for major updates, Microsoft gives its runtime libraries different names, so in that case it wouldn't be an issue.)

  2. This doesn't make sense, because no function has been requested from the dll being loaded. (Adam is right.)

  3. Therefore, the missing function was expected to be found not in the dll which is being explicitly loaded by the LoadLibrary command, but in a dependent dll which is being implicitly loaded at the same time, because the first dll requires it. (Zebrabox was close.)

  4. A dependent dll is a dll that is "statically" linked to the library being explicitly loaded, via an import library, or .lib file, included on the linker step of the explicitly loaded dll. (I bet you didn't know that a "dynamic link library" could be "statically linked." Well, now you do.)

  5. If you have multiple versions of the same dll in different folders, then this could also be a search path problem (as zebrabox suggests). Dll path search order is a complicated subject in itself: see http://msdn.microsoft.com/en-us/library/ms682586(VS.85).aspx . It depends on operating system, among other things. The safest bet, where practical, is to put all the potential problem dlls in the same folder as your exe.

  6. Dependent dlls can also have their own dependent dlls, which can make this problem very difficult to resolve. Depends might help, but if it doesn't, try filemon. The last dll that's successfully read before your error message is the one that's the wrong version.