我有以下源代码:

const ClassTwo g_classTwo;

void ClassOne::first()
{
    g_classTwo.doSomething(1);
}

void ClassOne::second()
{
    g_classTwo.doSomething(2);
}

产生以下objdump:
void ClassOne::first()
{
 1089c50:   e1a0c00d    mov ip, sp
 1089c54:   e92dd800    push    {fp, ip, lr, pc}
 1089c58:   e24cb004    sub fp, ip, #4
 1089c5c:   e24dd008    sub sp, sp, #8
 1089c60:   e50b0010    str r0, [fp, #-16]
    g_classTwo.doSomething(1);
 1089c64:   e59f3014    ldr r3, [pc, #20]   ; 1089c80 <ClassOne::first()+0x30>
 1089c68:   e08f3003    add r3, pc, r3
 1089c6c:   e1a00003    mov r0, r3
 1089c70:   e3a01001    mov r1, #1
 1089c74:   ebffffe2    bl  1089c04 <ClassTwo::doSomething(int) const>
}
 1089c78:   e24bd00c    sub sp, fp, #12
 1089c7c:   e89da800    ldm sp, {fp, sp, pc}
 1089c80:   060cd35c    .word   0x060cd35c

01089c84 <ClassOne::second()>:

void ClassOne::second()
{
 1089c84:   e1a0c00d    mov ip, sp
 1089c88:   e92dd800    push    {fp, ip, lr, pc}
 1089c8c:   e24cb004    sub fp, ip, #4
 1089c90:   e24dd008    sub sp, sp, #8
 1089c94:   e50b0010    str r0, [fp, #-16]
    g_classTwo.doSomething(2);
 1089c98:   e59f3014    ldr r3, [pc, #20]   ; 1089cb4 <ClassOne::second()+0x30>
 1089c9c:   e08f3003    add r3, pc, r3
 1089ca0:   e1a00003    mov r0, r3
 1089ca4:   e3a01002    mov r1, #2
 1089ca8:   ebffffd5    bl  1089c04 <ClassTwo::doSomething(int) const>
}
 1089cac:   e24bd00c    sub sp, fp, #12
 1089cb0:   e89da800    ldm sp, {fp, sp, pc}
 1089cb4:   060cd328    .word   0x060cd328

两种方法都以pc相对偏移量加载g_classTwo的地址:ldr r3, [pc, #20],这对于第一种方法和第二种方法分别转换为0x060cd35c0x060cd328

为什么即使地址都指向同一个全局变量,地址也不同?

这些地址与同一符号07156fcc b g_classTwo的nm输出如何相关?

最佳答案

ClassOne::first()中,您有:

1089c64:   e59f3014    ldr r3, [pc, #20]   ; 1089c80 <ClassOne::first()+0x30>
1089c68:   e08f3003    add r3, pc, r3
1089c6c:   e1a00003    mov r0, r3
...
1089c80:   060cd35c    .word   0x060cd35c

ClassOne::second()中,您有:
1089c98:   e59f3014    ldr r3, [pc, #20]   ; 1089cb4 <ClassOne::second()+0x30>
1089c9c:   e08f3003    add r3, pc, r3
1089ca0:   e1a00003    mov r0, r3
...
1089cb4:   060cd328    .word   0x060cd328

在这两者中,r0this指针(g_classTwo)。如您所见,将字面量池中的地址加载到r3后,将其加到pc以获得r0

ClassOne::first()中,您将获得r0 = pc + r3 = 0x01089c70 + 0x060cd35c = 0x07156fcc

ClassOne::second()中,您将获得r0 = pc + r3 = 0x01089ca4 + 0x060cd328 = 0x07156fcc

因此,对于this来说,指针都是0x07156fcc,它是g_classTwo的地址。

关于c++ - 程序集,全局变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39590382/

10-13 21:46