AT&T-X86: C-Assembly Relation

Just like how C is compatible with C++, Assembly is compatible with C. Though unlike the C-C++ relation, C actually almost IS assembly. Whenever you compile C code the compiler first turns it into a intermediate language and then turns that intermediate language into assembly based on you system details. The assembly code later gets assembled and linked to become the actual binary file. So this mainly means two things:

  1. you can generate assembly code from C code.
  2. C functions and variables are actually assembly variables and you can call C functions in assembly and vise versa (in most cases)

Generating assembly code from C code

edit

The gcc command:

gcc -S FILE.c -o FILE.s

(Where 'FILE' is the name of you file)

This command will take your C file and compile it as normal, but will stop when it has an assembly file that then becomes the output.

Using C and Assembly Functions Interchangeably

edit

Because C libraries and programs get compiled to assembly / machine-code, assembly programs can access those compiled C functions. The same way C functions can, after they are compiled access assembly functions.

Inline Assembly

edit

C has the 'asm' function that takes an assembly code block as a parameter, the compiler will preserve this code during compilation for it to end up as part of the resulting assembly code.

The "Hello, World!" program written this way would look like this:

int main(){
    asm("
        .data
        foo:   .string	"Hello, World!\n"
        
        .text
        	leaq	foo(%rip), %rax
        	movq	%rax, %rdi
         	call	puts@PLT
         	movl	$0, %eax
        	ret
    ");

Next: Registers & exit codes