DLL: what's the difference between static and non static global variables?
I'm writing a DLL in C and it uses some global variables.
I'm wondering what's the difference between using the static specifier or not. If I don't use it, does it mean that the variable is not going to be shared among processes using the DLL but it is going to be shared among the threads of a process? If I use it, doesn't mean that each process using the DLL is going to share the variable so I have to use some synchronization mechanism in order to avoid conflicts? And in this case, what happends with the threads of each process? Do they also share the variable?
Now suppose I want to allocate memory dinamically for a global variable during the execution of one the functions of the DLL, do I have to use GlobalAlloc, HeapAlloc or LocalAlloc, considering both cases, static and non static global variables?
Yes, my avatar is stolen
The static specifier, when not used in a function, only means that the variable name is only visible(in scope) in the current file. In every other way it is equivalent to a global variable.
Just like a global variable, it can be used from multiple threads. Some sort of synchronization will typically be required.
By default a variable in a DLL will not be shared amongst different processes. Each process will gets its own copy. To share a variable you must instruct the compiler to put it in the shared data segment. The method of doing this varies from compiler to compiler. Due to security considerations, putting a variable in the shared data segment is not a good idea. The recommended alternative is to use a file mapping.
>> Now suppose I want to allocate memory dinamically for a global variable during the execution of one the functions of the DLL, do I have to use GlobalAlloc, HeapAlloc or LocalAlloc, considering both cases, static and non static global variables? <<
I think you're asking which of these functions will let you share dynamically allocated memory amongst different processes. The answer is none of them. To share memory amongst different processes you should use a file mapping. If you do need to use one of these functions instead of new or malloc, you should use HeapAlloc as the others are obsolete.
Using Shared Memory in a Dynamic-Link Library
Search: dll share memory createfilemapping
Last edited by anonytmouse; 10-02-2004 at 12:23 AM.
Non-static and static global variables in a DLL is only specific to the address space of the process that maps the DLL. The attribute of non-static and static global is the same.