转换后的代码不执行给定的操作 [英] The code after conversion does not execute a given action
问题描述
我承担了根据AT& T语法将特定代码从C ++转换为ASM的任务,因此我从简单的示例开始,遇到了第一个问题.
I was given a task to convert a certain code from C++ to ASM based on AT&T syntax, so I started with simple examples and encountered the first problem.
我从中开始练习的代码
void func() {
int num = 1;
std::cout << "before: " << num << std::endl;
num = num << 3;
std::cout << "after: " << num << std::endl;
}
给出结果:
before: 1
after: 8
我的翻译变量num是第一个局部变量,因此应位于地址-4(%ebp)
my translation variable num is first local variable so it should be in address -4(%ebp)
void func() {
int num = 1;
std::cout << "before: " << num << std::endl;
asm (
"mov -4(%ebp), %eax \n"
"sall $3, %eax \n"
"mov %eax, -4(%ebp) \n"
);
std::cout << "after: " << num << std::endl;
}
给出结果:
before: 1
after: 1
为什么此代码对num var没有影响?
why this code has no effect on num var ?
推荐答案
您正在编写的代码是特定于实现的.在您的情况下,该代码可能无法正常工作,因为您正在使用32位寻址寄存器的 ebp
,而在使用 rbp 64>的64位计算机上运行时代码>.
The code you are writing is very implementation specific. In your case the code likely doesn't work because you are using ebp
which is a 32-bit addressing register, while you are running on a 64-bit machine, which uses rbp
.
但是,您使用的方法不正确.您可以编写纯汇编程序,也可以使用正确的(扩展的)C内联汇编程序来正确地与局部变量进行接口.否则,一旦您经历了一些更改,代码就会中断.
HOWEVER you are approaching this incorrectly. Either you write pure assembly, or you use the correct (extended) C inline assembly, that correctly interfaces with local variables. Else the code will break as soon as you change something, as you have experienced yourself.
根据此答案内联汇编程序应如下所示:
according to this answer the inline asm should look like:
asm ( "assembly code"
: output operands /* optional */
: input operands /* optional */
: list of clobbered registers /* optional */
);
所以您的代码看起来像
asm (
"mov %0, %%eax;"
"sal $3, %%eax;"
"mov %%eax, %1;"
:"=r" (num)
:"r" (num)
:"%eax"
);
但是,您无需指定和使用 eax
,因此可以将代码简化(并阐明)为
However, you don't need to specify and use eax
, thus the code could be simplified (and clarified) to
asm (
"sal $3, %[num];"
:[num] "+r" (num)
);
这篇关于转换后的代码不执行给定的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!