Search code examples
c++visual-studio-2013linkerstatic-linkingdynamic-linking

Why visual studio needs a static library (.lib) for dynamic linking?


I want to use some dll in my project ( VS2013 - c++ ),

I gave the path of dll and headers using "project->properties->vc++ directories", and after building the project, linker errors (common "unresolved external symbol") appears. the problem can be solved by giving the .lib file to the linker!

But why static library (.lib) is needed for dynamic linking???


Solution

  • It is an import library, which contains definitions of exports, that resides inside DLL and name of that DLL (*).

    You can use LIB with the /DEF option to create an import library and an export file. LINK uses the export file to build a program that contains exports (usually a dynamic-link library (DLL)), and it uses the import library to resolve references to those exports in other programs.

    And also:

    In most situations, you do not need to use LIB to create your import library. When you link a program (either an executable file or a DLL) that contains exports, LINK automatically creates an import library that describes the exports. Later, when you link a program that references those exports, you specify the import library.

    Dynamic libraries are loaded at runtime (on application startup) - linker does not check where some particular symbol resides in DLL. Header says __dllimport - "this symbol is an extern, it should be imported from somewhere". Lib says "I know where this symbol is - it resides in XXX.dll, so look there after startup".


    (*) I saw a lot of people, that were trying to change names of .lib and corresponding .dll and expected, that it will work. Contents of .lib is the reason why it didn't.