xorl %eax, %eax

Intel syntax on GCC

with 2 comments

Many people usually ask for Intel syntax support in GCC’s inline assembly functions. The native syntax for GCC as you already know is AT & T and as you can see in this example:

#include <stdio.h>

int
get_random(void)
{
    __asm__("movl $42, %eax");
}
int
main(void)
{
    return printf("The answer is %d.\n", get_random());
}

Nothing special is needed to compile this inline assembly, and in addition to this, it is 100% C99 valid source code according to GCC’s C99 implementation. Of course its output is:

sh-3.2$ gcc asm1.c -std=c99 -pedantic -o asm1
sh-3.2$ ./asm1
The answer is 42.
sh-3.2$

Now, if you desperately need Intel syntax (I can’t see the reason but anyway). You can use this way which is also documented but most people rarely use the documentation:

#include <stdio.h>

int
get_random(void)
{
    asm(".intel_syntax noprefix\n"
        "mov eax, 42           \n");
}
int
main(void)
{
    return printf("The answer is %d.\n", get_random());
}

First of all, notice the use of asm() instead of __asm__(). Next, mind the first declaration when using Intel syntax. The subsequent code is the same but of course in Intel syntax. Now, since this is not native to the GCC, you’ll need an additional GCC option which you can see here to compile it:

sh-3.2$ gcc asm2.c -o asm2 -masm=intel
sh-3.2$ ./asm2
The answer is 42.
sh-3.2$

As you can see from the gcc(1) man page:

 -masm=dialect
     Output asm instructions using selected dialect.  Supported choices
     are intel or att (the default one).  Darwin does not support intel.

Anyway, hope this will be useful to some folks using Intel syntax.

Written by xorl

January 1, 2009 at 23:29

Posted in C programming

2 Responses

Subscribe to comments with RSS.

  1. This post proved to be very helpful to me when I needed it most. However, on my system (gcc 4.6.2, Windows 7), I dropped the “.intel_syntax noprefix” but still compiled fine. Any reason why you used it?

    Michael Kwayisi

    January 13, 2013 at 19:28

  2. This is to ensure that GNU Assembler will handle the below assembly code as Intel syntax and noprefix indicates that you can use registers without using ‘%’ prefix. Of course it could work but it’s better to declare this in order to be sure that it will work as suggested by the documentation.

    xorl

    May 18, 2013 at 12:58


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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s