如何获得C ++函数的大小? [英] How can I get the size of a C++ function?

查看:140
本文介绍了如何获得C ++函数的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得C ++中函数的大小?

How can I get the size of a function in C++?

假设我有一个函数:

void f()
{
/*do something*/
}

...通过 f 的大小,我的意思是代码的大小 / *做某事* / ,从指向 f 的指针开始。

...By "size of f", I mean the size of the code /*do something*/, starting from the address indicated by a pointer to f.

推荐答案

你不能。它甚至可能不是一个明确定义的概念。例如,考虑以下代码:

You can't. It may not even be a well-defined concept. For example, consider the following code:

int f(int a) {
    return (3*a)+1;
}

int g(int a) {
    return (2*a)+1;
}

我怀疑这个例子在实践中会发生,因为它不会是一个优化,但编译器允许引入计算 a + 1 的代码块,然后返回,并从<$的每个入口点跳转到该块c $ c> f 和 g (在每种情况下执行乘法运算后)。那么 f 的大小是多少?它应该包括共享块的大小吗?一半大小?在C ++中声明函数 f 有一个大小是没有意义的。

I doubt it happens in practice for this particular example, because it wouldn't be an optimization, but the compiler is permitted to introduce a block of code that computes a+1 then returns, and jump to that block from each of the entry points of f and g (after doing a multiplication in each case). What then would be the size of f? Should it include the size of the shared block? Half that size? It just doesn't make sense in C++ terms to claim that the function f has a size.

指向f的指针不一定是函数f的地址。它确实提供了一种到达 f 的入口点的方法,但是例如在交互模式下的ARM处理器上,指向由Thumb代码组成的函数的指针实际上是第一条指令的地址加1.实际上,当执行跳转到函数时,CPU的指针的lsb被屏蔽掉,但该位告诉CPU切换到Thumb模式而不是ARM模式。所以指针的值不是函数的地址(虽然它接近)。无论如何,函数的入口点不一定是在它的开始 - 如果你的编译器创建常量池或类似的,它们可以在可执行代码之前。

Also, a "pointer to f" may not simply be the address of the function f. It certainly provides a way to get to the entry point of f, but for example on an ARM processor in interworking mode, a pointer to a function consisting of Thumb code is actually the address of the first instruction, plus 1. In effect, the lsb of the pointer is masked off by the CPU when performing the jump to the function, but that bit tells the CPU to switch into Thumb mode rather than ARM mode. So the value of the pointer is not the address of the function (although it's close). Anyway, the entry point of a function need not necessarily be the at the start of it - if your compiler creates constant pools or similar, they could precede the executable code.

可能有平台特定的方法来检查可执行文件(文件,或加载到内存后,或两者),并说什么代码与什么C ++函数相关联。毕竟,这是调试信息是什么。但是没有办法在标准C ++中这样做,并且标准不需要存在任何这样的机制。

There may be platform-specific ways of examining your executables (either the files, or after loading into memory, or both), and saying what code is associated with what C++ functions. After all, it's what debug info is for. But there's no way of doing that in standard C++, and the standard doesn't require that any such mechanism exists.

这篇关于如何获得C ++函数的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆