Search code examples
cgccassemblyx86inline-assembly

Can I use Intel syntax of x86 assembly with GCC?


I want to write a small low level program. For some parts of it I will need to use assembly language, but the rest of the code will be written on C/C++.

So, if I will use GCC to mix C/C++ with assembly code, do I need to use AT&T syntax or can I use Intel syntax? Or how do you mix C/C++ and asm (intel syntax) in some other way?

I realize that maybe I don't have a choice and must use AT&T syntax, but I want to be sure..

And if there turns out to be no choice, where I can find full/official documentation about the AT&T syntax?

Thanks!


Solution

  • If you are using separate assembly files, gas has a directive to support Intel syntax:

    .intel_syntax noprefix      # not recommended for inline asm
    

    which uses Intel syntax and doesn't need the % prefix before register names.

    (You can also run as with -msyntax=intel -mnaked-reg to have that as the default instead of att, in case you don't want to put .intel_syntax noprefix at the top of your files.)


    Inline asm: compile with -masm=intel

    For inline assembly, you can compile your C/C++ sources with gcc -masm=intel (See How to set gcc to use intel syntax permanently? for details.) The compiler's own asm output (which the inline asm is inserted into) will use Intel syntax, and it will substitute operands into asm template strings using Intel syntax like [rdi + 8] instead of 8(%rdi).

    This works with GCC itself and ICC, but for clang only clang 14 and later.
    (Not released yet, but the patch is in current trunk.)


    Using .intel_syntax noprefix at the start of inline asm, and switching back with .att_syntax can work, but will break if you use any m constraints. The memory reference will still be generated in AT&T syntax. It happens to work for registers because GAS accepts %eax as a register name even in intel-noprefix mode.

    Using .att_syntax at the end of an asm() statement will also break compilation with -masm=intel; in that case GCC's own asm after (and before) your template will be in Intel syntax. (Clang doesn't have that "problem"; each asm template string is local, unlike GCC where the template string truly becomes part of the text file that GCC sends to as to be assembled separately.)

    Related: