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.