shared data in shared libraries
Hi all,
How can I have a shared variable in a shared library, which would be the only copy of the variable for the entire process. To give an e.g of what I want to achieve, I have a process P which links to libraries S1 and S2. S1 also depends on S2. A variable in S2 is to be used by both S1 and P, and I need a single copy instead. How can I do this ? -- Cheers Arvind |
The only way to share data between two difference processes is to use shared memory.
The APIs you're interested in include: mmap () ... or .. shmat () Using "shared memory" has *nothing* to do one way or the other with using "shared libraries" (although Windows .dll implementation confuses the issue somewhat). Here's a good tutorial: http://fscked.org/writings/SHM/shm.html <= Note: Linux supports both the BSD and SysV styles |
I dont think you understood my question correctly. I have not mentioned that the data is to be shared between two different processes.
AFAIK, variables (global) in a shared library have just one copy even though they may be used by different libraries of the same process. I was just a bit confused about this when I read about some of the gcc attributes for variables. Thanks anyways.. |
I presume we are talking about C or C++ here. In this case, there generally will be an include file that goes with the library, and that include file will have variable declarations in it. For your variable to be shared, it would be an extern declaration in the include file, and would match an exported symbol in the library.
|
It's all about linking! I'd put the variable in S2, build S2 first, build S1 and link it to S2, then build P and link it to both S1 and S2. That should work! As long as two binaries (library or executable) are linked to the same library, only one copy of its contents should be present for both to use, provided both binaries are themselves linked to each other.
ta0kira PS An example: Code:
//library1.h Code:
//library1.c Code:
//library2.h Code:
//library2.c Code:
//main.c Code:
> gcc library1.c -shared -o library1.so |
Also look at:
http://www.redhat.com/magazine/011sep05/features/gcc/ which gives some hints about gcc and flags that can aid the right "aliasing" (to handle globals). This was got by googling "gcc+globals" |
arvind.ayyangar -
Quote:
|
Quote:
ta0kira |
All times are GMT -5. The time now is 03:58 PM. |