Why EXACTLY does the compiler need help from dllimport?

extern "C" __declspec(dllimport) void __stdcall func(); //func() is in a DLL file and called by an executable

Many articles say that dllimport makes more efficient code by bypassing a jump.
But why is there a jump at the first place?
Short answer: because there is not enough room for the linker to fill in with a function pointer.

Long answer:
the compiler doesn’t know whether func() is from dll or not, and it assumes it’s not(to save space and time). The compiler leaves a slot at the spot where func() is called for the linker to fill in with func()’s address. If it’s a non-dll function, no problem. If it IS a dll function, the linker doesn’t know the function’s address; it only knows the pointer pointing to this address(IAT entry). Here is the linker’s solution: using a stub.
The linker fills the slot with the address of the stub. The stub’s code has JMP to jump to where the function pointer points to(in IAT).
This explains why stub(jump) is needed. Of course if the compiler knows it’s a dll function, it doesn’t need the stub, because the compiler can simply leave the slot big enough for the linker to fill it with the function pointer(and ‘DWORD PTR’, but ignore it to keep it simple).

Comments are closed.
%d bloggers like this: