Disassembling C code to see the assembly language

We’ve been talking about assembly language in class recently and I’ve found a nice way of comparing source code with the assembly that the compile outputs. This is C, a compiled language.

int main() {
  divmod(26, 5);
}

int divmod (int dividend, int divisor) {
  int quotient = 0;
  while (dividend - divisor >= 0) {
    dividend = dividend - divisor;
    quotient = quotient + 1;
  }
}

The code divides 26 by 5 to give a quotient of 5 and remainder of 1, which is left stored in the dividend variable.

(This file was saved as divmod.c and then compiled using gcc, which is probably already installed on Mac computers. If you’re on Windows, you are advised to install the Community Edition of Microsoft Visual C++.)

Now, using a utility called objdump, which is preinstalled on my Linux laptop, I can now output the assembly code that was generated by the compiler. The output file of the compiler is called a.out, so that is the input to objdump. The flags tell objdump to include the source code intermixed with the assembly code, which is very handy for us!

The command to disassemble the compiled code is:

objdump -Sd --dwarf=info a.out

This provides a whole load of output, but in amongst it you can find the assembly code for the divmod function:

objdump output

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s