C ++编译器如何编译变量名? [英] How does a C++ compiler compile variable names?
问题描述
我明白我没有说清楚。我认为,我的怀疑,可以总结在这:
在可执行文件(机器代码)如何表示变量?它们是静态内存地址吗?
用代码表示:
int x = 5;
//一堆代码
cin>> y;
cout<< x + 1;
每个机器上的程序如何知道哪个地址将保存值5,保持输入的值,向现在保存的值添加1,最后打印相同的值。
- João
这里是一个简单的程序在C:
int main {
int a = 5;
int b = 7;
int c = a + b;
return 0;
}
如果使用 gcc -m32 -S -O0 -o main.s main.c
在Linux下,你会得到类似这样的东西
.filemain.c
pre>
.text
.globl main
.type main,@function
main:
.LFB0:
/ * %ebp是基本指针寄存器* /
pushl%ebp
movl%esp,%ebp
/ *这里我们为变量保留空间* /
subl $ 16,%esp
/ * a的地址是%ebp - 4 * /
movl $ 5,-4(%ebp)
/ * b的地址是% ebp - 8 * /
movl $ 7,-8(%ebp)
/ * a + b * /
movl -8(%ebp),%eax $ b b movl -4(%ebp),%edx
addl%edx,%eax
/ * c的地址是%ebp - 12 * /
movl%eax,-12 (%ebp)
/ * return 0 * /
movl $ 0,%eax
leave
ret
可以看到,在这种情况下,变量的地址被计算为函数的基指针的偏移量。如果启用优化,变量的值可以存储在寄存器中。
I understand I did not make myself clear. My doubt, I think, could be summed up in this:
In an executable file(machine code) how are "variables" represented? Are they static memory addresses? Does the compiler gives each one a specific "name" (or just keeps the one you gave them)?
Expressed in code:
int x=5; //Bunch of code cin>>y; cout<<x+1;
How does the program in each and every machine knows which address is going to hold the value 5, to hold the inputed value, to add 1 to the value it now holds and finally print that same value.
--João
解决方案Here is a simple program in C:
int main() { int a = 5; int b = 7; int c = a + b; return 0; }
If you compile it with
gcc -m32 -S -O0 -o main.s main.c
under Linux, you'll get something like this.file "main.c" .text .globl main .type main, @function main: .LFB0: /* %ebp is a Base Pointer Register */ pushl %ebp movl %esp, %ebp /* Here we reserve space for our variables */ subl $16, %esp /* a's address is %ebp - 4 */ movl $5, -4(%ebp) /* b's address is %ebp - 8 */ movl $7, -8(%ebp) /* a + b */ movl -8(%ebp), %eax movl -4(%ebp), %edx addl %edx, %eax /* c's address is %ebp - 12 */ movl %eax, -12(%ebp) /* return 0 */ movl $0, %eax leave ret
As you can see, in this case, variables' addresses are calculated as offsets of a base pointer of a function. If you enable optimisations, variables' values may be stored in registers.
这篇关于C ++编译器如何编译变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!