共享库和主应用程序中

时间:2016-11-06 06:16:32

标签: c linux shared-libraries

所以我有一个共享库的代码 testlib.c

#include <stdio.h>

int **z;

void f(int *x)
{
    z = &x;
    printf("TESTLIB.C: z = %p, *z = %p, **z = %d\n", z, *z, **z);
}

void f2(void)
{
    printf("TESTLIB.C: z = %p, *z = %p, **z = %d\n", z, *z, **z);
}

testlib.h

void f(int *);
void f2(void);

应用程序文件 test.c

#include <stdio.h>
#include "testlib.h"

int main()
{
    int y = 1;
    int *x = &y;

    printf("TEST.C: &x = %p, x = %p\n", (void *)&x, (void *)x);
    f(x);
    f2();

    return 0;
}

我将共享库testlib.c编译为

gcc -shared -fPIC testlib.c -o libtest.so

和test.c as

gcc test.c -o test -L. -ltest

LD_LIBRARY_PATH=.

现在我执行./test的输出是

TEST.C: &x = 0x7ffcd99e9f40, x = 0x7ffcd99e9f3c
TESTLIB.C: z = 0x7ffcd99e9f18, *z = 0x7ffcd99e9f3c, **z = 1
TESTLIB.C: z = 0x7ffcd99e9f18, *z = 0x7f71cb8af168, **z = 0
TEST.C: &x = 0x7ffcd99e9f40, x = 0x7ffcd99e9f3c, *x = 1

为什么第二行z的值不等于第一行的&x值?根据我的理解,共享库被加载到与加载它的进程相同的地址空间中?

此外,为什么*z会在调用f2()时发生变化?在调用z期间,有没有办法保留f()中存储的值?

0 个答案:

没有答案
相关问题