How to declare a global variable in the main program so that you can access it in the dll?

  • Set the _export mark (and in extern libraries), and you can link it (automatically, which is more difficult, or manually). - nick_n_a
  • one
    But it would be better not to do this, because after changing the main program it is necessary to link the library, otherwise there will be falls, and this will require linking the main program to its own source. Global variables and without such distortions are rather inconvenient and dangerous. It is better to pass a variable or a reference to it to a function that should use this variable. - Artemy Vysotsky

2 answers 2

The best way to access a variable in the main program from a DLL is to do this in the library for a function that will receive the address and continue to work with the variable through that address. Example:

 __declspec(dllexport) void useData(T* data) { // используем data-> ... } 

In the program, call this function, passing the address of the global variable:

 T gData; useData(&gData); 

    In summary, as I did: in the main function, exe declared the function from the dll as follows:

     __declspec(dllexport) void _stdcall setHwnd(HWND*, HHOOK*); 

    Then, in dll I got two static - variables that I will store the values ​​I need. And further, I called this function in the main program:

     setHwnd(&hwnd_main, &hCBTHook); 

    In dll, the function looks like this:

     __declspec(dllexport) void _stdcall setHwnd(HWND* hwnd, HHOOK* hhook) { hwnd_main = *hwnd; hCBTHook = *hhook; } 

    And it works. Thank.

    • Something you do not have enough parameter names. And apparently self-attribution occurs, i.e. useless operation. - αλεχολυτ
    • @alexolut just when I wrote the message, did not copy the implementation of the function from the studio, but added with my hands, forgetting about the parameters) - Range