Intel syntax on GCC
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.
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
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
You *ONLY* have to add the -masm=intel directive to the command line to switch to intel syntax. All that putting the directive in the asm statement manually can achieve is to confuse the error handling if you forget to put the directive on the command line. The only reason for putting the assembler directive in the asm statement is to try to mix the two assembler styles. Even if you don’t manage to confuse the assembler you’ll probably confuse yourself.
The C99 and pedantic options have nothing to do with it; it’s perfectly acceptable to put intel style in either asm statement.
Robert de Bath
May 31, 2014 at 22:36