Search code examples
cgccdlllinkercygwin

Link against a Windows .dll+.lib file combination with GCC under Cygwin?


I know how to link against libraries in Unix-ish contexts: If I'm working with .a or .so files, I specify the root search directory with -L/my/path/to/lib/ and for libMylib I add -lMyLib.

But what if I have

  • a .dll (e.g. in the Windows\System32 directory)?
  • a .dll (in Windows\System32) and a .lib (someplace else)?

These DLLs are by some other party; I don't have access to their sources - but do have access to the corresponding include files, against which I manage to compile.


Solution

  • If you can link against a .lib in Cygwin or MinGW, then you can (indirectly) link against a DLL.

    In the MSVC world, it is not unusual to create an import library along with a DLL. It is a static library (.lib) that loads the DLL and wraps the interface of the DLL. You just call the wrapper functions in the (static) import library and let the import library do all the DLL-related things.

    • For the Windows API, there are import libraries in the WindowsSDK.
    • For your own MSVC DLLs, MSVC can automatically generate the import libraries when you build the DLL.
    • For a third party DLL, you can build a static wrapper library based on the corresponding header files.

    Linking against the .lib file in Cygwin or MinGW is possible. Example:

    g++ -o myprg myprg.o -lShlwapi
    

    This links against Shlwapi.lib. (The library must be in the local directory or in the library path of the linker.)

    Linking against import libraries of DLLs works the same way.

    Note 1: Keep in mind the different ABIs and name mangeling. However, calling plain C functions in DLL or LIB files will work in most cases.

    Note 2: Keep in mind that g++ requires the libraries to be specified in the correct order.