Mixing C and Assembly


Defining in assembly and using in C
The assembly code which defines functions and variables:
# define a global variable asm_var and export it so that C code can use.
.data
.global asm_var
asm_var:
.long

# define a function asm_fun and export it so that C code can use.
.text
.global asm_fun
asm_fun:
    ret;
C code:
void asm_fun();
extern int asm_var;

int x;
void main()
{
	asm_fun();
	asm_var++;
}
Points to understand:

Defining in C and using in assembly
C code
void fun()
{
}
Assembly code:
.text
.global main
main:
    call fun
    ret;
Points to understand:

Mixing assembly inside C code

There are few things that you can not do in pure C code at all. For those things you have to use assembly. For example if you want to raise a hardware exception, then you need to write assembly instruction. C does not provide any syntax to raise hardware exception. To avoid to write code in separate assembly file and call from C code, C provide a way to insert assembly code inside a C code. This is done by asm keyword.

Here is an example:
int main()
{
	asm("int $3");
	return 0;
}
Assembly which is generated form this C code will be:
    .text
.globl main
    .type   main, @function
main:
    pushl   %ebp
    movl    %esp, %ebp
    int $3
    movl    $0, %eax
    popl    %ebp
    ret

up