October 21, 2010

Inline assembly basics

Filed under: C — Tags: , — shijitht @ 1:34 am

Inline assembly functionality allows embedding assembly code in C program. This is like an inline function, where the corresponding value gets substituted. Here assembler substitutes our assembly code in proper place with no change. GCC follows AT&T systax for assembly code.

AT&T syntax

  1. Register prefixed with % and $ for immediate/constant.(%eax and $10)
  2. Source operand comes first.(opcode source destination)
  3. Size of operand as a suffix to opcode. i.e. b -> byte, w -> word,
    l -> long.(movl)
  4. Indirect memory reference using parenthesis, ‘( ‘ and ‘ )’.(  (eax)  )

In C

syntax:   asm(” assembly code “);
function asm is used to write assembly code in C.

int fun()
 asm("mov $24, %eax");
int main()
 int n = fun();
 printf("%d\n", n);
 return 0;

In test.c function fun has no return statement. But it returns 24. When a function returns, its return value is places in eax register. But we can explicitly set eax using asm. So a value can be returned without a return statement. The move instruction used is darkened above.

Operation which are very difficult or unable to perform in C can be achieved easily using inline assembly. Rotation of a block of bytes is done in a single step using  asm.( ror or rol ). But in C, it takes an effort. And all machine level instructions can be used, which can’t be produced with gcc. eg: logical and arithmetic shift. Architecture dependent coding and optimization is done using inline assembly. Speed of code can be further improved with hand written assembly.


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

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

Create a free website or blog at WordPress.com.

%d bloggers like this: