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 it.
.global asm_var

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

int x;
void main()
Points to understand:

Defining in C and using in assembly
C code
void fun()
Assembly code:
.global main
    call fun
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 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:
.globl main
    .type   main, @function
    pushl   %ebp
    movl    %esp, %ebp
    int $3
    movl    $0, %eax
    popl    %ebp


Want to learn (C/C++ internals) directly from the author using video call? Learn more

Do you collaborate using whiteboard? Please try Lekh Board - An Intelligent Collaborate Whiteboard App