How to set a variable in GCC with Intel syntax inline assembly?

牧云@^-^@ 提交于 2019-12-17 07:33:56

问题


Why doesn't this code set temp to 1? How do I actually do that?

int temp;
__asm__(
    ".intel_syntax;"
    "mov %0, eax;"
    "mov eax, %1;"
    ".att_syntax;"
    : : "r"(1), "r"(temp) : "eax");
printf("%d\n", temp);

回答1:


You want temp to be an output, not an input, I think. Try:

  __asm__(
      ".intel_syntax;"
      "mov eax, %1;"
      "mov %0, eax;"
      ".att_syntax;"
      : "=r"(temp)
      : "r"(1) 
      : "eax");



回答2:


This code does what you are trying to achieve. I hope this helps you:

#include <stdio.h>

int main(void)
{
    /* Compile with C99 */
    int temp=0;

    asm
    (   ".intel_syntax;"
        "mov %0, 1;"
        ".att_syntax;"
        : "=r"(temp)
        :                   /* no input*/
    );
    printf("temp=%d\n", temp);
}



回答3:


You have to pass an argument to GCC assembler.

gcc.exe -masm=intel -c Main.c
gcc.exe Main.o -oMain.exe

And you have C code like this:

#include <conio.h>
#include <stdio.h>

int myVar = 0;

int main(int argc, char *argv[])
{
    asm("mov eax, dword ptr fs:[0x18]");
    asm("mov eax, dword ptr ds:[eax+0x30]");
    asm("movzx eax, byte ptr ds:[eax+0x2]");
    asm("mov _myVar, eax");

    if(myVar == 1) printf("This program has been debugged.\r\n");
    printf("Welcome.\r\n");
    getch();

    return 0;
}

Don't forget to add prefix underscore (_) for every variables in asm() keyword, or it won't recognize it.

And keyword asm() use prefix '0x' for every hexadecimal integer, not suffix 'h'.



来源:https://stackoverflow.com/questions/5397677/how-to-set-a-variable-in-gcc-with-intel-syntax-inline-assembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!