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 Answer
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.
-
I am trying what you have suggested. My problem is that when I am building in debug mode no lib file is generated. Only dll file is generated. how can I generated lib file in debug version. May 22, 2014 at 11:05
-
Your comment seems to suggest that you get a lib file in the release build, but not in the debug build. Is that right? If so, make sure you've set the same linker options in both builds (except, of course, for those that need to be different between release and debug.) May 23, 2014 at 6:16
-
The linker will normally generate the import library automatically if your DLL contains any function with the __declspec(dllexport) attribute, or if you export functions explicitly with a DEF file. Maybe your __declspec(dllexport) is excluded by the compiler because it's surrounded by #ifndef(_DEBUG) or something like that? May 23, 2014 at 6:19
-
Ah... this could be the case. Actually I am not using __declspec(dllexport) attribute at all. This is because I am exporting class. May 25, 2014 at 11:58
-
1Ah, I see. In the context of a DLL, that's not "exporting". Basically, exporting a function from a DLL means to publish its address in an exports table so that clients can find it and link to it at load time. To export your function, use the __declspec(dllexport) attribute. This will cause the linker to list your function in the DLL's export table, and to create the import library for you. The same principles apply to exporting a class. May 27, 2014 at 6:58