Global variable in shared library

681 views Asked by At

Do you know how to share a global variable in a shared library ?

I got a problem with that. I declare in my header file

int a;

And I will use it in some C file than I will compile as a shared library. But the update of A in the files seems to not be shared and the variable's change are not effective.

I read in some post that is because the data segment isn't shared, but, I need it. Have you an idea of how do that ?

Thanks!

1

There are 1 answers

0
user35443 On BEST ANSWER

I read in some post that is because the data segment isn't shared, but, I need it. Have you an idea of how do that ? Data segment isn't shared indeed. I'm sorry, but that's how it works.

Many of the modern operating systems load a shared library into memory, so that a program using it can read the value of its memory locations until it performs a write.

In the moment it does so, operating system may apply COW (copy on write) policy, and create an exact copy of library´s memory specifically for the use of the program that tried to modify it.

Other programs therefore can't see any of the changes the first program did.

If you want to have a memory shared between processes, one must refer to operating system. For example, Linux uses the shared memory IPC, and you must use it´s API to achieve what you want. Don't get discouraged, it's very simple.