cgcccompilationinline-assemblyintel-syntax

How can I run C-code with assembly inserts


I have C-program with assembly insert. Here is code: main.c:

#include <stdio.h>

int f() {
    int a = 0, b;
    __asm__ (".intel_syntax noprefix\n\t"
             "mov edx, 1\n\t"
             :"=r"(b)
             :"r"(a)
             :"eax"
            );
    return b;
}

int  main() {
    printf("%d", f());
}

I have found out how to compile this code (gcc -std=c11 -S main.c -o main), but when i run it (./main) - here is a problem in terminal: bash: ./main: Permission denied.

When I try to compile it without -S flag, I get many unreasonable mistakes:

/tmp/ccw3H0Mb.s: Assembler messages:
/tmp/ccw3H0Mb.s:23: Error: Instruction does not exist: «movl%edx,-4(%rbp)»
/tmp/ccw3H0Mb.s:24: Error: Instruction does not exist: «movl4(%rbp),%eax»
/tmp/ccw3H0Mb.s:46: Error: Instruction does not exist: «movl$0,%eax»
/tmp/ccw3H0Mb.s:48: Error: Instruction does not exist: «movl%eax,%esi»
/tmp/ccw3H0Mb.s:49: Error: Garbage «(%rip)» after expression
/tmp/ccw3H0Mb.s:50: Error: Instruction does not exist: «movl$0,%eax»
/tmp/ccw3H0Mb.s:52: Error: Instruction does not exist: «movl$0,%eax»

What is the error and how can I fix it to run my code correctly? Thanks! :)


Solution

  • All I needed was just adding -masm=intel to the compilation command, and, of course, I removed -S flag (thanks to fuz). It is important because I am using Intel syntax, so gcc must be awared about it.

    Now it looks like:

    gcc -std=c11 -masm=intel main.c -o main