1

I am confused of the add instruction in x86.

this is the original c code:

int a = 1;
int b = 2;
int c = 0;

void add() { 
c = a + b;      
}

I translated it to assembly language and got this:

add:
pushl   %ebp
movl    %esp, %ebp
movl    a, %edx
movl    b, %eax
addl    %edx, %eax // add instruction
movl    %eax, c    // why is it stored in eax?
popl    %ebp
ret

Isn't the result of edx+eax supposed to be stored in edx? Why is it stored in eax? Or could it be that my compiler handles things differently?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
  • *How* did you "translate it to assembly language"? – unwind May 02 '18 at 09:13
  • 3
    it's AT&T/gas syntax, where destination argument is second (it's reversed to Intel syntax found in Intel documentation, i.e. gas `addl %edx, %eax` = `add eax,edx` in Intel) There are several different assembly dialects for x86 in common use, so check what kind of tutorials/books you would like to read and which tools they use, check availability of tools, and stick to single dialect for beginning. It's not that difficult to learn the differences later, as the underlying machine code is of course the same one, but it's unneeded hassle in the beginning. – Ped7g May 02 '18 at 09:13
  • 2
    i used gcc -S -m32 -fno-asynchronous-unwind-tables -o main0.s main0.c –  May 02 '18 at 09:14
  • I personally prefer Intel syntax and open source tools, so I'm usually around tools like NASM, edb-debugger, etc... and use gcc only for C/C++ parts of code (you can still switch gcc to produce Intel-like dialect when using `-S`, but it's not exactly NASM one, and the GNU toolchain is generally expecting to be used with original AT&T/gas syntax, so you may run into some corner case problems, when you are using it with the intel syntax option -> it's certainly good enough to just check out something quickly, like `-S`, but I wouldn't use it to compile assembly files in some project). – Ped7g May 02 '18 at 09:19
  • https://stackoverflow.com/q/199966/4271923 in case you are curious. – Ped7g May 02 '18 at 09:21
  • 2
    @Ped7g: I like to link [How to remove "noise" from GCC/clang assembly output?](https://stackoverflow.com/q/38552116) to show how to get asm out of gcc, because very early on it has a link to Matt Godbolt's CppCon2017 talk [“What Has My Compiler Done for Me Lately? Unbolting the Compiler's Lid” ](https://youtu.be/bSkpMdDe4g4) – Peter Cordes May 02 '18 at 09:49
  • @Ped7g i followed the link you sent me and tried changing it to intel syntax but it just created a unreadable assembly code first I used gcc -S -masm=intel main.c then I used gcc -S -masm=intel -fno-pic -fno-asynchronous-unwind-tables main.c because I am using a 64 bit OS but I still get the same results –  May 02 '18 at 17:45
  • @momonosuke "Unreadable assembly code"? Can you give an example or a link to such code? –  May 02 '18 at 19:44

0 Answers0