Exporting '& Importing classes and functions when building multiple DLLs

Randy More's previous article (posted on March 8, 1998) provided a solution to solve the problem of using one extension dll in another. Basically, he suggested that we redefine the macro AFX_EXT_CLASS in one dll's header file before including a header file for classes exported by a second dll , and restore the previous macro definition afterwards.

His solution does not work in the situation where dll A uses classes in dll B and dll B also uses classes in dll A. I have found a much simpler solution which solves these problems elegantly.

Suppose we want to build a dll called MyDllA. First we define the following macros:


#ifdef BUILD_MYDLLA
#define MYDLLA_EXPORT __declspec(dllexport) 
#else
#ifdef USE_MYDLLA
#define MYDLLA_EXPORT __declspec(dllimport)
#else
#define MYDLLA_EXPORT 
#endif
#endif

Then we declare classes, functions, and data in MyDllA using the macro MYDLLA_EXPORT, for example:

class MYDLLA_EXPORT MyClass
{
...
};

When compiling MyDllA, we define the macro BUILD_MYDLLA in the project setting. When compiling a dll that uses classes in MyDllA, we define the macro USE_MYDLLA in its project setting. The same trick can be applied when build MyDllB, MyDllC, etc. Note that the source code doesn't have to be changed if we decide to make MyDllA a static library instead (in that case, don't define the macros BUILD_MYDLLA and USE_MYDLLA when compiling the project).

Date Last Updated: April 18, 1999