Search notes:

masm example: function

The following example tries to demonstrate how a function can be created with masm and then be called from a C program.
This example needs to be compiled on a x86 (not a x64) environment.

add_3.asm

func.asm defines a function, named _add_3 that adds the first three parameters (arguments) and returns it via the eax register.
.model  flat

; PUBLIC  _add_3

_TEXT  SEGMENT

_add_3  PROC

    push  ebp
    mov   ebp, esp

    mov   eax, DWORD PTR  8[ebp]  ;  The 1st argument is ebp +  8
    add   eax, DWORD PTR 12[ebp]  ;  The 2nd argument is ebp + 12
    add   eax, DWORD PTR 16[ebp]  ;  The 3rd argument is ebp + 16


    pop   ebp
    ret   0

_add_3 ENDP

_TEXT  ENDS

END          ; END directive required at end of file
Github repository about-masm, path: /functions/add_3/x86/add_3.asm

main.c

main.c just calls the function and prints its result.
#include <stdio.h>

#pragma warning (default : 4255)

int add_3(int,int,int);

int main(void) {
    printf("add_3(11,7,24) returned %d\n", add_3(11,7,24));
}
Github repository about-masm, path: /functions/add_3/x86/main.c

Makefile

The Makefile for nmake to compile the project.
prog.exe: main.obj add_3.obj
	cl /nologo /Feprog.exe main.obj add_3.obj 
	prog.exe

main.obj: main.c
	cl /W4 /nologo /c main.c

add_3.obj: add_3.asm
	ml /nologo /c add_3.asm
Github repository about-masm, path: /functions/add_3/x86/Makefile

See also

Stackframe and base pointers

Index