我实际上是在将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("%llun",test);
printf("%llun",*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
只是为了有类似问题的人:
我决定使用 getter & setter,因为使用动态库访问主程序的功能没有问题,只有变量。
在 mylib.c 中:
test2 = getTest();
在主 C 中:
uint64_t* getTest(){
return &test;
}
更新
我终于找到了解决这个getter和setter的方法。您面临的问题是您要定义变量两次,就我而言,这发生在对extern
关键字的误解期间。为了解决您的问题,您需要在main.h
中将变量声明为 extern,例如:
extern uint64_t test;
extern uint64_t *test2;
下一步是定义main.c
中的变量,例如:
int main(...) {
test = 1;
test2 = &test;
}
最后从您的mylib.h
中删除外部声明
以下SO帖子导致了我的解决方案:链接