Search code examples
c++windowsdllshared-librariesdeclspec

Pros and Cons of Using .def Files


I don't understand this paragraph :

Exporting functions in a .def file gives you control over the export ordinals. When you add an exported function to your DLL, you can assign it a higher ordinal value than any other exported function. When you do this, applications that use implicit linking do not have to relink with the import library that contains the new function. This is very convenient if you are designing a DLL for use by many applications because you can add new functionality and also ensure that it continues to work correctly with the applications that already rely on it. For example, the MFC DLLs are built by using .def files.

Why application doesn't have to relink with the import library in case of the usage of a .def file instead of __declspec(dllexport) in the case of a function adding into the dll ?

cf https://learn.microsoft.com/en-us/cpp/build/determining-which-exporting-method-to-use


Solution

  • That is because of some specifics of MSFT implementation of shared objects (or DLLs). In Microsoft world, in order to import function into your process, you need not only the shared code itself (.dll), but you also need the special 'import' library - the .lib file. This file is statically linked into your application (as it is a static library). This library provides 'glue' between function names and function ordinals.

    Normally, every time you release a new version of DLL, all applications which use it will have to be relinked with the new, accompanying version of static import library (.lib) to be able to use this new DLL library. This is due to the fact that function ordinals are generally no longer valid after you have created the new library. However, if you are using .def file, you can assign ordinals manually, and ensure the ordinals remain the same for previously available functions - and thus .lib file will still be valid.