C 和汇编 __asm 不工作

标签 c gcc assembly

我找到这段代码把栈指针放入EAX寄存器(应该是C中return用的寄存器)

#include <stdio.h>
unsigned long get_sp(){
    unsigned long stp;
    __asm{
        mov
        eax, esp
        }
}

void main(void){
printf("\n0x%x", get_sp());
}

我用 Geany 试过了,但没用!! 然后我按照编译器日志,以这种方式更改了代码:

#include <stdio.h>

unsigned long get_sp(void);

int main(void){
printf("\n0x%ld", get_sp());
return 0;
}


unsigned long get_sp(void){
    unsigned long stp;
    __asm{
        mov eax, esp
    }
}

这次我的 main 没问题,但是 other 函数就悲剧了!!! 它不识别 __asm。 未知类型名称“mov”.... 未使用的变量'eax'... 它似乎需要 __asm() 而不是 __asm{},就像函数的正常调用一样。 有人可以帮助我吗? 聚苯乙烯 我有 debian 64 ....64 架构可能有一些问题??

最佳答案

正确的 GCC 代码应该是

__attribute__((noinline,noclone))
unsigned long get_sp(void) {
  unsigned long stp;
  asm(
    // For x86_64: "movq %%rsp, %0"
    "movl %%esp, %0"
    : "=r"(stp)
  );
  return stp;
}

关于C 和汇编 __asm 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30904654/

相关文章:

c - C 中的内联汇编 - 了解编译结果

c - 有谁知道为什么 gcc 4.8.4 在无限循环中优化这段代码?

assembly - 为什么在使用 PUSH 或 POP 指令时不鼓励使用 ESP 寄存器?

c - 如何计算周期?

c - 在 C 中排序链表的问题

c++ - 从 ‘const char*’ 到 ‘char*’ [-fpermissive] 的无效转换

c - 理解一个shellcode例子

c - 如何使用 GCC 在 asm() 中编写多个汇编语句而不使用 "\t\n"分隔每一行?

assembly - 如果数字不 >= 0,为什么代码加 7

c++ - 什么是虚拟适配器