Nathaniel Flath
Nathaniel Flath

Reputation: 16045

C++ global variables across DLLs

I wrote something to simulate the getopt.h library for a Windows application, and part of this is a global variable. This worked fine when I compiled the program as a single application; however, when I split off the getopt library and linked against it, my program started getting segfaults. Investigating this, it seems that accessing the variable from outside the DLL doesn't work and returns an invalid pointer; is there anything I can do to fix this?

Edit:If I enter a function in the DLL in the debugger, the variable has the correct value - acessing it directly from the application gives a different value.

Upvotes: 4

Views: 4067

Answers (2)

Mysticial
Mysticial

Reputation: 471529

What's probably happening is that you haven't setup the dllexport/dllimport correctly. The result is that you're ending up with different copies of the same variable. (one in the DLL and one outside)

Within the DLL, you need to compile with dllexport to expose the variable to the client application.

Then in the client application, you need to declare the same variable as dllimport. Then it will link against the one that's in the DLL.

This is slightly unfortunate because the same headers are usually used for the DLL and the client. So the usual work-around is this:

#ifdef COMPILE_DLL
#define DLL_EXPORT  __declspec(dllexport)
#else
#define DLL_EXPORT  __declspec(dllimport)
#endif

EDIT:

Can you confirm whether or not you have two copies of the same variable? Try printing out the addresses from both inside the DLL and from outside.

Upvotes: 5

jdigital
jdigital

Reputation: 12296

Consider adding a function to your DLL that returns the value of the variable.

Upvotes: 3

Related Questions