Function Calling and Strings in Assembly

Calling Functions in Assembly

The instruction "call" is used to call another function.   The function can then return using "ret" (call stores the return address to jump back to on the stack).  Here's an example:

mov edi,7 ; pass a function parameter
call otherFunction  ; run the function below, until "ret"
add eax,1 ; modify returned value

otherFunction: ; a function "declaration" in assembly
	mov eax,edi ; return our function's only argument

(Try this in NetRun now!)

External Functions in Assembly

By default, the assembler assumes functions are defined later in the same file, like above.  To call an external function, such as NetRun's "print_int", or a standard C library function like "exit", you need to tell the assembler the function is "extern".  "extern" isn't actually an instruction--it doesn't show up in the disassembly--it's just a message to the assembler, often called a pseudoinstruction.

extern exit ; tell assembler function is defined elsewhere
call exit ; call the function

(Try this in NetRun now!)

In C++ or C, header files tend to contain declarations of extern functions, and so play the same role as extern in the assembler.

Strings in Assembly 

In plain C, you can put a string on the screen with the standard C library "puts" function:


(Try this in NetRun now!)

You can expand this out a bit, by declaring a string variable.  In C, strings are stored as (constant) character pointers, or "const char *":

const char *theString="Yo!";

(Try this in NetRun now!)

Internally, the compiler does two things:

In assembly, these are separate steps:

Here's an example:

mov rdi, theString ; rdi points to our string
extern puts  ; declare the function
call puts    ; call it

theString:    ; label, just like for jumping
	db `Yo!`,0  ; data bytes for string (don't forget nul!)

(Try this in NetRun now!)

In assembly,  there's no obvious way to tell the difference between a label designed for a jump instruction (a block of code), a label designed for a call instruction (a function), a label designed as a pointer (like a string), or many other uses--it's just a pointer!

CS 301 Lecture Note, 2014, Dr. Orion LawlorUAF Computer Science Department.