How do I compile the asm generated by GCC?

前端 未结 7 1983
南方客
南方客 2020-12-04 06:18

I\'m playing around with some asm code, and something is bothering me.

I compile this:

#include 

int main(int argc, char** argv){
  p         


        
相关标签:
7条回答
  • 2020-12-04 06:50

    You can embed the assembly code in a normal C program. Here's a good introduction. Using the appropriate syntax, you can also tell GCC you want to interact with variables declared in C. The program below instructs gcc that:

    • eax shall be foo
    • ebx shall be bar
    • the value in eax shall be stored in foo after the assembly code executed

    \n

    int main(void)
    {
            int foo = 10, bar = 15;
            __asm__ __volatile__("addl  %%ebx,%%eax"
                                 :"=a"(foo)
                                 :"a"(foo), "b"(bar)
                                 );
            printf("foo+bar=%d\n", foo);
            return 0;
    }
    
    0 讨论(0)
  • 2020-12-04 06:54
    nasm -f bin -o 2_hello 2_hello.asm
    
    0 讨论(0)
  • 2020-12-04 06:57

    gcc can use an assembly file as input, and invoke the assembler as needed. There is a subtlety, though:

    • If the file name ends with ".s" (lowercase 's'), then gcc calls the assembler.
    • If the file name ends with ".S" (uppercase 'S'), then gcc applies the C preprocessor on the source file (i.e. it recognizes directives such as #if and replaces macros), and then calls the assembler on the result.

    So, on a general basis, you want to do things like this:

    gcc -S file.c -o file.s
    gcc -c file.s
    
    0 讨论(0)
  • 2020-12-04 06:59

    Yes, gcc can also compile assembly source code. Alternatively, you can invoke as, which is the assembler. (gcc is just a "driver" program that uses heuristics to call C compiler, C++ compiler, assembler, linker, etc..)

    0 讨论(0)
  • 2020-12-04 07:05

    You can use GAS, which is gcc's backend assembler:

    http://linux.die.net/man/1/as

    0 讨论(0)
  • 2020-12-04 07:08

    Yes, You can use gcc to compile your asm code. Use -c for compilation like this:

    gcc -c file.S -o file.o
    

    This will give object code file named file.o. To invoke linker perform following after above command:

    gcc file.o -o file
    
    0 讨论(0)
提交回复
热议问题