2

我实际上正在将 Linux 应用程序移植到 Mac OS X。我的问题是我可以访问变量但不能访问指针。

我以这种方式声明了变量main.h

uint64_t test;
uint64_t *test2;

mylib.h

extern uint64_t test;
extern uint64_t *test2;

mylib.c我以这种方式访问​​变量:

printf("%llu\n",test);
printf("%llu\n",*test2);

第一个printf()没有任何问题,但第二个给了我这个错误:

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000008

有人知道为什么会这样吗?

我的ggc命令行具有以下标志:

gcc -Wall -g -fPIC -c main.c gcc -shared -Wl,-undefined,dynamic_lookup -o mylib.so mylib.o
4

1 回答 1

0

仅针对有类似问题的人:

我决定使用 getter 和 setter,因为使用动态库访问主程序的函数没有问题,只是变量。

在 mylib.c 中:

test2 = getTest();

在 main.c 中:

uint64_t* getTest(){
    return &test;
}

更新

我终于找到了解决这个 getter & setter 的方法。您面临的问题是您定义了两次变量,在我的情况下,这发生在对extern关键字的误解期间。要解决您的问题,您需要在main.h例如:

extern uint64_t test;
extern uint64_t *test2;

下一步是在您的示例中定义变量main.c

int main(...) {
    test = 1;
    test2 = &test;
}

最后从您的mylib.h

以下 SO 帖子导致了我的解决方案:link

于 2012-12-14T11:54:16.630 回答