# define a global variable asm_var and export it so that C code can use it.
.data
.global asm_var
asm_var:
.long
# define a function asm_fun and export it so that C code can use it.
.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:void fun()
{
}
Assembly code:
.text
.global main
main:
call fun
ret;
Points to understand: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 instructions. C does not provide any syntax to raise hardware exceptions. To avoid writing code in separate assembly files and call from C code, C provides 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