【问题标题】:How to get and assign the address of exit library function to a global variable?如何获取退出库函数的地址并将其分配给全局变量?
【发布时间】:2013-07-24 11:35:33
【问题描述】:

我想获取出口库函数的地址,然后将此地址分配给一个全局变量。

  //test3.c

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 
  4   int fp = &exit;
  5 
  6 int main(){
  7   printf("fp=%d\n",fp);
  8   return 0;
  9 }

但是当我使用 gcc 编译上面的 test3.c 程序时出现了一个错误。

$ gcc -o test3 test3.c
test3.c:4:12: warning: initialization makes integer from pointer without a cast [enabled by default]
test3.c:4:3: error: initializer element is not computable at load time

当我在主函数中获取并分配出口地址给局部变量时,没有错误。

  //test4.c

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 
  4 int main(){
  5   int fp = &exit;
  6   printf("fp=%d\n",fp);
  7   return 0;
  8 }

我可以打印结果:

$ gcc -o test4 test4.c
test4.c: In function ‘main’:
test4.c:5:12: warning: initialization makes integer from pointer without a cast [enabled by default]
$ ./test4
fp=4195408

如何将出口地址分配给全局变量?

【问题讨论】:

标签: c global-variables shared-libraries exit


【解决方案1】:

您应该使用正确的类型声明fp(即指向采用int 并且不返回任何内容的函数的指针):

void (*fp)(int) = &exit;

不知道你想用printf 做什么。如果要打印地址,请使用 %p 而不是 %d

【讨论】:

  • 谢谢。但是如果我将exit的地址分配给main函数中的局部变量,就没有错误了。
  • 是的,但是有一个大警告应该引起您的注意:initialization makes integer from pointer without a cast
  • 我认为警告不是最重要的问题。我可以使用 gcc 选项来抑制这个警告。
  • 当然可以取消警告,但那是个坏主意。该警告不是问题,而是解决方案提示。它准确地告诉你出了什么问题:分配一个指向int 的指针。所以解决方案是修复int变量的类型。
  • 我尝试使用 void(*fp)(int) = &exit.它已经编译成功。但是为什么要在全局范围内使用函数指针呢?出口的地址好像只有链接后才能得到。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-06
  • 2017-06-25
  • 2022-01-19
  • 1970-01-01
相关资源
最近更新 更多