This tutorial will cover how to use a function written in assembler in your C/C++ programs on a Linux/Unix system.
I am using nasm to assemble a simple program that outputs 1 character.
That function will need to be declared global inside of the assembly code:
CODE
section .data
msg: db "-" ; the output charactor
len: equ $-msg ; the length of msg
section .text
global _junk ; because this will be used with c code,
; we can't redeclare start, so I've just called it Junk
global _line ; <-- This is our target function!
_junk:
call _line ; we never enter here through c anyhow...
xor ebx, ebx
mov eax, 1
int 80h
_line:
mov eax, 4
mov ebx, 1
mov ecx, msg ; Load register ecx with our character
mov edx, len ; Load register edx with the length
int 0x80
ret ; return to the c code
Now we'll use nasm to create something that gcc can use later...
nasm -f elf dash o line.o line.asm It's important to make the output file of type elf. Otherwise gcc will complain that it doesn't know what it is.
cpp
#include <stdio.h>
extern void _line(void); // Load the _line function from assembler output file
void output(void); // This is kind of overkill, but I think it helps make the point clear
int main(void) {
printf("\n"); // Clear the slate with a fresh line for outputing some text
output(); // Display our text function
printf("\n"); // Another fresh line, just for the assembler text
_line(); // Output the character from the assembler code
output(); // Bring it all home, with another example showing our text from the c code
printf("\n"); // One more return, just for good measure
return 0; // And we're all set!
}
void output(void) {
printf("This output is from the c code:\n");
}
Now we just need to compile the c code, along with the output from the assembler code.
gcc dash o main main.c line.oFinally, we can run the executable created by gcc, & the output should look like the following:
QUOTE
#./main
This output is from the c code:
-
This output is from the c code:
A
HUGE thanks to baavgai & perfectly.insane!!!