1

I've heard that import libraries have "stubs" so the executable knows which dll and function we want. Now my question is: What are those stubs? What do they look like? How does the executable set the pointers to right places in the DLL? And how does it know if we are talking about normal library or import library since they both are .lib files?

2 Answers2

8

The MSVC linker does not link directly to a DLL, it can only link to a static library (.lib).

Very roughly speaking, an import library is a normal static library, that has a stub function for every DLL exported function.

For example, if a DLL has a function void func1() and exports func1, the corresponding import library will contain a stub function void __imp__func1() { __asm { jmp dword ptr func1; } }

At run time, the "jump" will take the address of func1 from the import table. That's why a stub is needed.

The declaration void __declspec(dllimport) func1(); in your application will in fact refer to __imp__func1().

You can bypass this whole mechanism altogether and call LoadLibrary and GetProcAddress to get the address of func1 at run time. It will have the same effect.

rustyx
  • 80,671
  • 25
  • 200
  • 267
1

That depends on the compiler (linker) and platform you are using.

I.e. on Windows OS, a shared library is usually a .DLL file,
if you want to link to it (other than dynamically loading it and resolve its symbols at runtime), you need the corresponding .LIB file, that is the stub library.

Basically a stub library is a static library that re-maps all the symbols exported by the DLL (with __declspec(dllexport)) to symbols present in the stub and that can be found and statically linked within your program by using __declspec(dllimport).

roalz
  • 2,699
  • 3
  • 25
  • 42
  • So is __declspec(dllexport) a function from Windows API or is it an instruction that is in the Visual Studio? – Daniel Nyman Feb 17 '17 at 10:43
  • @Daniel Nyman: '__declspec' is a keyword (as far as I know specific for Visual Studio), 'dllexport' and 'dllimport' are attributes of that keyword. See more at: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx – roalz Feb 17 '17 at 10:46
  • [__declspec](https://msdn.microsoft.com/en-us/library/dabb5z75.aspx) is a keyword, that assigns a Microsoft-specific storage-class attribute. – IInspectable Feb 17 '17 at 10:47