Lib and DLL linking to an exe error “cannot read a

2020-02-12 02:53发布

问题:

I have a general question about how .dll/.libs are suppose to be used. I am creating a .dll to be used for my project, however, I noticed that when I go to compile I need to statically link the .lib associated with the .dll for the project to compile (otherwise there is the linking error "fatal error LNK1107: invalid or corrupt file: cannot read at 0x300"). So later when I go redistrobute my project, then update it in the future, will I need to ship a new .exe and a new .dll rather than only a new .dll? If that is the case, then why bother using .dll's?

回答1:

The .lib contains stubs for the functions etc. that are exported by the DLL. You link the .lib into your EXE and now your EXE knows how to call the functions. But of course there's no function there - the calls go nowhere. At load time, when the operating system loads your EXE it also loads your DLL, and then it patches the EXE - where the EXE calls into the stub, the loader replaces that with a call into the real function in the DLL.

Normally you do not need to ship the .lib to your customers. However, if your customers want to write their own EXEs that use your DLL then you will need to send them the .lib so that they can link their EXE against it.

Linker error LNK1107 means that you've tried to link to the DLL rather than to the .lib. That's always wrong, because by definition a DLL is linked dynamically at runtime, rather than statically at build time.