GCC - linking to a library in another folder works

2019-09-08 00:02发布

问题:

I'm working on a C++ project that generates several EXEs and several DLLs. For the sake of neatness, I'd like to have those DLLs generated in a Lib folder, so the built project would look like this:

MyProject
----myExe1.exe
----myExe2.exe
----Lib
    ----myLib1.dll
    ----myLib2.dll

I was able to successfully get the DLLs built into the Lib folder, and I was able to successfully link to the DLLs in their new location using -L..\bin\Lib in the linking command for the EXEs. However, when I go to actually run the EXEs, they complain that they can't find the DLLs in question.

From the research I've done, it looks like even though I can link to libraries in other folders, loading them still requires them to be in the same folder as the binaries.

GCC, linking libraries, not found? suggests that this is simply the way things are meant to be, but mentions "the system has to be able to find the dll; i.e. it has to be in the current working directory, in a directory that is in the path, or its directory has to be added to a special environment variable used for this thing". What "special environment variable" is being referenced (I'm assuming it's not %PATH% or the comment wouldn't have specifically mentioned the path earlier), and is there a way I can set it so my DLLs can be properly loaded?

回答1:

Complete information about DLL search order is on MSDN site: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682586%28v=vs.85%29.aspx

Short version: During DLL loading the OS searches it in the following order:

  1. The directory from which the application loaded.
  2. The system directory (i.e. C:\Windows\System32)
  3. The 16-bit system directory.
  4. The Windows directory (i.e. C:\Windows)
  5. The current directory.
  6. The directories that are listed in the PATH environment variable.

So if you want to separate your exe file from dll then you have to put the folder with the libraries into PATH. Another option is dynamic DLL loading using LoadLibraryEx http://msdn.microsoft.com/en-us/library/windows/desktop/ms684179%28v=vs.85%29.aspx