Thursday, May 7, 2009

Exporting a Global Variable from a DLL

Lets say you want to export a global variable of type int and use it in another application. You need to do it as follows.

1. In the header file where you are going to declare your variable do this.
   extern DLL_EXTERN int i;

2. In the .c or .cpp file, you need to define it like this.
   DLL_EXTERN int i = 10;

You should make your pre-processor settings such that DLL_EXTERN is equal to __declspec(dllexport).

3. Now in your application, where you are going to consume this variable, you need to set your pre-processor options such that DLL_EXTERN is equal to __declspec(dllimport).

For functions, not having __declspec(dllimport) does not give any compile/link errors. But of course it helps generate better code as with this the compiler knows that the function resides in a DLL and hence it can avoid the level of indirection that is there when a function call is done across the boundary of a DLL. But its a MUST that you have __declspec(dllimport) in front of variables as without that you will get the famous "unresolved external symbol" errors.

1 comment:

Raikanta said...

Thanks for the post. That was the clearest set of instructions I found on the subject, and the suggestion works like a charm.