Access EXE's global variables from DLL

On linux, I can compile DLLs (shared objects) as well as executables that use them. I can even access globals and classes that are defined in the EXE from the DLL, and vice versa, simply with the 'export' keyword. flawlessly.

The Problem: But on Windows (using MinGW), no matter what I do, I'm completely unable to access global variables which defined in the EXE, from the DLL. On Linux, this is no sweat, but what's Windows' problem?

I also need to extend classes in the dll with base class method definitions defined in the exe.

Ive heard that on Windows, you need to use declspec(dllimport) and declspec(dllexport). I can compile with CygWin+MinGW/g++4.5.3 as well as "Pure Windows" with MinGW/g++4.7.2 *without* the declspecs. So what's the decljunk for? Is this really just something for MSVC or other compilers?

Here's some Windows code to show what the problem is. The DLL's global variable is accessible to the EXE just fine, but the EXE's global variable is not accessible to the DLL - compilation complains it is an undefined reference.

main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include "myLib.h"
#include <stdio.h>

int exe;

int main ( void ) {
	lib = 5;
	foo( 5 );
	return 0;
}

void A::foo( void ) {
	printf("asd\n");
	return;
}


myLib.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef MYLIB_H
#define MYLIB_H

extern int  lib;
extern int  exe;

void foo( int bar );

class A {
public:
	void foo( void );
};

#endif // MYLIB_H  


myLib.cpp
1
2
3
4
5
6
7
8
9
10
#include "myLib.h"

int lib;

void foo( const int bar ) {
	lib = bar;
	exe = bar;
	A a;
	a.foo();
}


build.bat
1
2
3
g++ -c myLib.cpp -DMYLIB_SDK=1 -D_WIN32=1
g++ -shared -o libmyLib.dll myLib.o -DMYLIB_SDK=1 -D_WIN32=1 
g++ main.cpp -o main.exe -L. -lmyLib -Wl,-rpath=./ -D_WIN32=1


edit: I tried using --enable-runtime-pseudo-reloc --allow-shlib-undefined options when compiling the DLL and G++ complains that --allow-shlib-undefined is an unrecognized option.
Last edited on
http://comments.gmane.org/gmane.comp.gnu.mingw.user/14207

I found that page which explains the same deal, and everyone there basically says that it's just plain impossible to access EXE's globals from within the DLL's code. I'm not ready to give up yet; would really love someone to shed some light on this.

update: The one and only way I have found to access EXE variables from a DLL in Windows is to use the Win32 API function GetProcAddress() to get the address of a function and call it manually. The first argument to GetProcAddress() is the return of LoadLibrary() (If functions you wish to use are wrapped in export "C" blocks it's much more intuitive naming) I'm still not sure what the declspec(dllexport) is for.

This link helped: http://www.transmissionzero.co.uk/computing/advanced-mingw-dll-topics/
Last edited on
Topic archived. No new replies allowed.