What is the difference between dllexport and dllimport?

Visual C++DllImportExport

Visual C++ Problem Overview


I'm just looking for a simple, concise explanation of the difference between these two. MSDN doesn't go into a hell of a lot of detail here.

Visual C++ Solutions


Solution 1 - Visual C++

__declspec( dllexport ) - The class or function so tagged will be exported from the DLL it is built in. If you're building a DLL and you want an API, you'll need to use this or a separate .DEF file that defines the exports (MSDN). This is handy because it keeps the definition in one place, but the .DEF file provides more options.

__declspec( dllimport ) - The class or function so tagged will be imported from a DLL. This is not actually required - you need an import library anyway to make the linker happy. But when properly marked with dllimport, the compiler and linker have enough information to optimize the call; without it, you get normal static linking to a stub function in the import library, which adds unnecessary indirection. ONT1 ONT2

Solution 2 - Visual C++

  • __declspec(dllexport) tells the linker that you want this object to be made available for other DLL's to import. It is used when creating a DLL that others can link to.

  • __declspec(dllimport) imports the implementation from a DLL so your application can use it.

I'm only a novice C/C++ developer, so perhaps someone's got a better explanation than I.

Solution 3 - Visual C++

Two different use cases:

  1. You are defining a class implementation within a dll. You want another program to use the class. Here you use dllexport as you are creating a class that you wish the dll to expose.

  2. You are using a function provided by a dll. You include a header supplied with the dll. Here the header uses dllimport to bring in the implementation to be used by the current program.

Often the same header file is used in both cases and a macro defined. The build configuration defines the macro to be import or export depending which it needs.

Solution 4 - Visual C++

Dllexport is used to mark a function as exported. You implement the function in your DLL and export it so it becomes available to anyone using your DLL.

Dllimport is the opposite: it marks a function as being imported from a DLL. In this case you only declare the function's signature and link your code with the library.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question1800 INFORMATIONView Question on Stackoverflow
Solution 1 - Visual C++Shog9View Answer on Stackoverflow
Solution 2 - Visual C++rpetrichView Answer on Stackoverflow
Solution 3 - Visual C++morechilliView Answer on Stackoverflow
Solution 4 - Visual C++Antoine AubryView Answer on Stackoverflow