Does global variable in main program conflict with global variable in dll with the same name?

You can define a global variable in a dll, and define another global variable with the same name in the main program that loads the dll. The two global variables won’t conflict with each other although they have the same  name. Both the dll and the main program compile without problem. Actually, they use two pieces of memory. Changing the value of one won’t affect the value of the other.

Then, how to use the global variable in the dll, in your main program? You may write the following code to use the global varibale in the dll as done for using global variable in another source file of the main program:

extern int aglobalvariable;

Unfortunately, you will get the linking error saying undefined reference to aglobalvariable.

To share a global variable between dll and a process loading this dll, you should export the variable from the dll using __declspec(dllexport) and importing it in the program loading the dll using __declspec(dllimport), and you will need to link the dll statically. How to link a dll statically? You should generate an import library when building the dll, then link this import library when building the main program,i.e.,

g++ -o mydll.dll mydll.c -shared -Wl,–out-implib,libmydll.a

g++ -o main main.c -lmydll -L .

If you do not use  __declspec(dllimport) when declaring a global variable in your main program, the variable is just an ordinary global variable for your main program. If you use __declspec(dllimport) in the main program but not use __declspec(dllexport) in the dll, you will get an “undefined reference” linking error because __declspec(dllexport) will generate a reference (the name is of the form:__imp_xxxx) to the variable in the import lib, that is to be linked against by the main program.

Comments are closed, but trackbacks and pingbacks are open.