CodeCamper CodeCamper - 1 month ago 4
C Question

How do I write the following inline Assembly Code in C using GCC

I was reading some answers and questions on here and kept coming up with this suggestion but I noticed no one ever actually explained "exactly" what you need to do to do it, On Windows using Intel and GCC compiler. Commented below is exactly what I am trying to do.

#include <stdio.h>

int main()
int x = 1;
int y = 2;
//assembly code begin
push x into stack; < Need Help
x=y; < With This
pop stack into y; < Please
//assembly code end
return 0;


Let the compiler choose the registers, using the k prefix to denote a 32-bit register for the int type (so it works as expected on x86-64) :

__asm__ ("pushl %k0\n\t"
         "movl %k1, %k0\n\t"
         "popl %k1"
         : "+r" (x), "+r" (y));

It's not necessary (and actually wrong) to specify any clobbered operands in this case.

It's also apparent that x,y are commutative here, i.e., swapping the operands should still yield the same result using: : "+%r" (x), "+r" (y) where % denotes that this operand and the next operand may commute.