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.
What’s probably happening is that you haven’t setup the
dllexport/dllimportcorrectly. 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
dllexportto 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:
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.