Search code examples
c++linker-errorsdllexport

When building a dll, can the lib be used for linking?


I wanted to create a C++ dll (to be used in a dot net application). Some functionality I needed was already implemented in another C++ dll.

The dll I was referencing was set up like this (including the comment):

extern "C"
{
  __declspec(dllexport) BOOL SomeFunctionToBeUsedExternally();
}
// internal functions
BOOL OtherFunctions();

I need to use one of the OtherFunctions in my code.

So, I added the proper include in my own code, added dependencies on the lib created by the dll above, and used the method I needed. As a result, of course, I got another __declspec(dllexport)... function.

It refused to link though, I got an error about the OtherFunction.

I verified everything, looked online - nothing seems to solve my problem.

Then, I added a __declspec(dllexport) in front of the function I needed, and it works.

I don't understand though. I thought, the dllexport marked functions will be exported to the dll, but aren't all functions sent to the lib ?

Why do I have to export functions to the dll, if I am not linking against the dll but against the lib ?


Solution

  • No, the linker does not automatically export all identifiers. The dllexport attribute tells the linker which identifiers are exported. Without this you would be forced to either export every identifier in the DLL or specify which identifiers should not be exported. When the linker creates the DLL it also creates an import library and includes information about which identifiers are exported based on that attribute.

    When you want to use a DLL you need link with the appropriate .lib file for good reason. The .lib file tells the linker which identifiers are exported, the name of the DLL they are in and other information. It is also possible to export identifiers from the DLL by ordinal instead of by name. In this case the linker still needs to match the identifier with the appropriate ordinal. This is only possible by having an accompanying library file that contains that information since it is not present in DLL's export table.