Linux 如何打印函数的地址?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10932910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 06:41:54  来源:igfitidea点击:

How to print the address of a function?

clinuxgccfunction-pointersgcc-warning

提问by alk

I let gcccompile the following example using -Wall -pedantic:

我让gcc编译下面的例子使用-Wall -pedantic

#include <stdio.h>

int main(void)
{
  printf("main: %p\n", main); /* line 5 */
  printf("main: %p\n", (void*) main); /* line 6 */

  return 0;
}

I get:

我得到:

main.c:5: warning: format ‘%p' expects type ‘void *', but argument 2 has type ‘int (*)()'
main.c:6: warning: ISO C forbids conversion of function pointer to object pointer type

Line 5 made my change the code like in line 6.

第 5 行让我像第 6 行一样更改了代码。

What am I missing to remove the warning when printing a function's address?

打印函数地址时,我缺少什么来删除警告?

采纳答案by R.. GitHub STOP HELPING ICE

This is essentially the only portable way to print a function pointer.

这本质上是打印函数指针的唯一可移植方式。

size_t i;
int (*ptr_to_main)() = main;
for (i=0; i<sizeof ptr_to_main; i++)
    printf("%.2x", ((unsigned char *)&ptr_to_main)[i]);
putchar('\n');

回答by Ben Voigt

This whole idea is indeed non-portable, since some systems use different sized pointers to code and data.

这整个想法确实是不可移植的,因为一些系统使用不同大小的代码和数据指针。

What you really need is platform-specific knowledge of how big a function pointer is, and a cast to an integral type of that size. Unfortunately, I don't think anyone has standardized a intfuncptr_tanalagous to intptr_twhich can hold any data pointer.

您真正需要的是特定于平台的关于函数指针有多大的知识,以及转换为该大小的整数类型。不幸的是,我认为没有人标准化了可以保存任何数据指针的intfuncptr_t类似物intptr_t



As R. notes in his answer, you can always treat the pointer as an array of (possibly signedor unsigned) char, this way you don't need any integral type of the correct size.

正如 R.在他的回答中指出的那样,您始终可以将指针视为 (可能signedunsigned)的数组char,这样您就不需要任何正确大小的整数类型。

回答by Fred Foo

It's right there in the warning: ISO C forbids conversion of a function pointer to an object pointer type, which includes void*. See also this question.

它就在警告中:ISO C 禁止将函数指针转换为对象指针类型,其中包括void*. 另请参阅此问题

You simply can't print the address of a function in a portable way, so you can't get rid of the warning.

您根本无法以可移植的方式打印函数的地址,因此您无法摆脱警告。

You can print a function pointer using @R..'s suggestion.

您可以使用@R.. 的建议打印函数指针。

回答by Lalaland

While converting a function pointer to a void pointer is technically dangerous, converting function pointers to void pointers is used in the POSIX standard, so it is almost sure to work on most compilers.

虽然将函数指针转换为 void 指针在技术上是危险的,但在 POSIX 标准中使用了将函数指针转换为 void 指针,因此几乎可以肯定它可以在大多数编译器上工作。

Look up dlsym().

抬头看dlsym()