I decided to start learning some inline assembly however I am left with a simple question for which I am unable to find a clear answer.
Take the following simple example which I found in a tutorial which performs a simple addition as such:
int one,two,out;
one = 1;
two = 2;
__asm__ ( "add eax, ebx;" : "=a" (out) : "a" (one) , "b" (two) );
Note that for the sake of my own sanity after working with intel syntax for a while, I configured GCC to use intel syntax instead of AT&T.
Now suppose I would want to leave out the "out" variable and just store the output in "one" instead (or "two" for all that matters).
How would I do this?
Use
__asm__ __volatile__(" add %0, %2": "=r" (one): "0"(one), "r" (two) )
By using "=r" and "r", you don't unnecessarily force the compiler to use a particular register, which helps register allocation. "0" means "use same as (output) argument 0".
Edit3: The two
argument is in %2
, not in %1
, which is just a second copy of one
(same register as %0
). Also fixed double %
when single should be used.
Edit2: I also added __volatile__
to ensure that the compiler doesn't move or omit the assembler code, which can happen if the compiler does not think your code does anything useful [typically because it produces no output that the compiler uses later on]. With __volatile__
the compiler is guaranteed to NOT move or remove the assembler code.
Edit1: Fix up syntax.
__asm__ ( "add eax, ebx;"
: "+a" (one)
: "b" (two) );
The "+"
modifier indicates a 'read/write' operand (and must be used in the output constraint).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With