How to process-global variable in C++?

Harsha_MR 1 Reputation point
2020-10-08T04:20:06.16+00:00

.h file:
extern int myGlobal;
void work();

.cpp file:
int myGlobal = 42;
void work(){ myGlobal++; }

When the .cpp file is put in a static library and more than one shared library (DLL) or executable links against the static library, each one has its own copy of myGlobal. work() would modify its own version of the variable.

is there a way to get a process-wide unique variable or pointer to that variable?

Developer technologies C++
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Castorix31 90,521 Reputation points
    2020-10-08T05:27:48.193+00:00

    You can use data_seg pragma

    For example, in an old DLL using global hooks, I have :

    #pragma comment(linker, "/section:.Shared,rws")  
    #pragma data_seg (".Shared")  
    static  HHOOK g_hHook = 0;  
    HWND    g_hWndNotify = NULL;  
    #pragma data_seg()  
    
    0 comments No comments

  2. RLWA32 49,536 Reputation points
    2020-10-08T10:41:22.92+00:00

    Another way to share memory between dlls - using-shared-memory-in-a-dynamic-link-library

    Shared sections may be simpler to implement but they do have security implications - Why .shared sections are a security hole

    Neither method of sharing memory between dlls will change the fact the each dll will contain its own copy of the variable from the linked-in static library. One possibility would be to wrap the static library in a dll. This wrapper dll would expose the methods and variables from the static library. Other dlls could then reference the wrapper dll without having to link with their own copy of the static library.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.