关于share library共享数据的问题!
我发现在share library中的全局变量,静态全局变量都是私有的,也就是说无法在多个加载这个库的进程中共享.我用google搜了一下,发现也有人遇到我这个问题,请问有人知道如何解决吗?
也就是说,如何实现进程A修改了一个共享库中定义的变量x,使另外一个也加载了这个共享库的进程中的x也发生变化.问题的英文描述如下:
Hi,
I wrote a shared library and I know the code of the
shared library will be shared between different
applications. However, the global data of the library
cannot be shared.
For example, the code of the shared library looks
like
// myshare.c
#include <stdio.h>
int global = 5;
void printGlobal()
{
printf("Global=%d\n",global);
}
void setGlobal(int g)
{
global = g;
}
I used the following command to create the library
$gcc -fPIC -shared -o libmyshare.so myshare.c
The user application 1 links with it
//u1.c
#include <stdio.h>
extern void setGlobal(int);
int main()
{
setGlobal(50);
return 0;
}
I used the following command to create u1
$gcc -o u1 u1.c -L. -lmyshare
The user application 2 links with it too
//u2.c
#include <stdio.h>
extern void printGlobal(int);
int main()
{
printGlobal();
return 0;
}
I used the following command to create u2
$gcc -o u2 u2.c -L. -lmyshare
Then, I run u2 and u1
$u2
Global=5
$u1
$u2
Global=5
It seems that from u1, setGlobal(50) does not affect
the
print out of u2, which means, when u1 and u2 link with
the shared library libmyshare.so, there are two
copies
of the global data in libmyshare.so. So the code is
shared,
but not the global data.
My question is: is there any way to share the global
data
within a shared library, i.e, both code and data can
be shared?
(I know I can use shared memory, but I wonder if we
can
do it using special compiler settings.)