以下是 gcc 和 Clang 为您的代码生成的内容:
main: # @main
xor eax, eax
ret
Godbolt上的代码
所以在这种情况下,我们实际上并没有早期或晚期绑定。相反,我们根本没有绑定到函数——你没有使用调用函数得到的结果(直接或通过指针),所以编译器根本没有生成任何代码来调用函数全部。
我们可以使用此订单上的代码修复它:
#include <iostream>
int add (int x, int y)
{
return x+y;
}
int main()
{
int a=add(5,6);//early binding
int (*p_add)(int,int)=add;
int b=p_add(5,19);
std::cout << b;
}
在这种情况下,编译器仍然会在编译时检测到函数的结果不依赖于任何内容,因此它会在编译时计算该值,并将其作为常量打印出来:
mov esi, 24
mov edi, OFFSET FLAT:_ZSt4cout
call std::basic_ostream<char, std::char_traits<char> >::operator<<(int)ant:
Godbolt上的代码
所以,我们仍然没有对函数真正的“绑定”。让它使用它直到运行时才知道的输入:
#include <iostream>
#include <cstdlib>
int add (int x, int y)
{
return x+y;
}
int main()
{
int x1 = rand();
int x2 = rand();
int a=add(x1, x2);//early binding
int (*p_add)(int,int)=add;
int b=p_add(x1,x2);
std::cout << b;
}
此源生成以下目标代码:
call rand
mov ebx, eax
call rand
mov edi, OFFSET FLAT:_ZSt4cout
lea esi, [rbx+rax]
call std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
编译器仍然知道指针始终指向一个特定的函数,因此即使源代码显示通过指针调用的函数,在目标代码中我们不通过指针调用函数......事实上,我们仍然根本不调用该函数。相反,函数体的代码是内联生成的。
要通过指针获得实际的函数调用,我们可以有一个指向两个不同函数中的任何一个的指针,并且直到运行时在特定情况下使用这两个函数中的哪一个才会很明显。例如:
#include <iostream>
#include <cstdlib>
int add (int x, int y)
{
return x+y;
}
int sub(int x, int y) {
return x-y;
}
int main()
{
int x1 = rand();
int x2 = rand();
int z = rand() % 2;
int (*p_add)(int,int) = z ? add : sub;
int b=p_add(x1,x2);
std::cout << b;
}
这(终于!)使通过指针的调用实际上作为通过指针的调用发生:
call rand
mov edx, OFFSET FLAT:sub(int, int) ; start by assuming we'll subract
mov esi, r12d
mov edi, ebp
test al, 1 ; then see if we have an odd or even number
mov eax, OFFSET FLAT:add(int, int)
cmove rax, rdx ; if necessary, point to add
call rax ; and finally call the function via the pointer
mov edi, OFFSET FLAT:_ZSt4cout
mov esi, eax
call std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
Godbolt上的代码
概括
如果在编译时很明显将调用哪个函数,编译器可能不会生成代码来通过指针调用该函数,即使源代码显示的是这样。