2013-01-31 47 views
3

可能重複:
How to access c variable for inline assembly manipulation操縱變量c

鑑於這種代碼:

#include <stdio.h> 

int main(int argc, char **argv) 
{ 
    int x = 1; 
    printf("Hello x = %d\n", x); 


    } 

我想訪問和操作變量x內聯彙編。理想情況下,我想使用內聯彙編改變它的值。 GNU彙編程序,並使用AT & T語法。假設我想將x的值更改爲11,在printf語句之後,我將如何去做這件事?

回答

4

asm()函數遵循該順序:

asm ("assembly code" 
      : output operands     /* optional */ 
      : input operands     /* optional */ 
      : list of clobbered registers  /* optional */ 
); 

並通過您的C代碼把11至x與組件:

int main() 
{ 
    int x = 1; 

    asm ("movl %1, %%eax;" 
     "movl %%eax, %0;" 
     :"=r"(x) /* x is output operand and it's related to %0 */ 
     :"r"(11) /* 11 is input operand and it's related to %1 */ 
     :"%eax"); /* %eax is clobbered register */ 

    printf("Hello x = %d\n", x); 
} 

可以通過避免修飾寄存器簡化上述彙編代碼

asm ("movl %1, %0;" 
    :"=r"(x) /* related to %0*/ 
    :"r"(11) /* related to %1*/ 
    :); 

您可以通過避免輸入操作數和通過usi從代替C納克從ASM本地恆定值:

asm ("movl $11, %0;" /* $11 is the value 11 to assign to %0 (related to x)*/ 
    :"=r"(x) /* %0 is related x */ 
    : 
    :); 

又如:compare 2 numbers with assembly