From the course: Advanced C Programming: Integrating C and Assembly Language

Adding C to assembly

- [Instructor] Just as you can call an assembly language function from within a C program, you can call C functions from assembly. This operation Works by linking the assembly and C modules. But unlike calling assembly from C, which is covered elsewhere in this course, I'm making the assembly module, the main module. Here you see the main assembly module. The C function is declared external message, here at line three. This instruction directs the linker to look elsewhere for the function. Should it be passed values or return a value, the code handles the overhead. Unlike in C, where a prototype says what's passed and returned, this declaration just states that there's a function out there, named message. At line 11, the program's entry point is declared. The LD linger uses underscore start, which you see another assembly code. Here, the entry is main because I'm using clang to link. More on that in a minute. The function is global. The bulk of the program loops five times, calling the C language message function at line 17. The value of register rcx must be saved here, pushed at line 16 and popped at line 18. Save important registers when you call a C language function. At line 22, the exit routine is called. Here's the C module which contains the message function. It's a void function and has no arguments. Symbol, just output a line of text. To build the program, I'll compile the C code, clang dash C to compile only, and the source code, file name, success. And now we'll assemble the assembly module using nasm dash f elf64 and its name. Both object code modules have been created. To link, I'll use clang, which I feel is best for linking mixed modules, clang and the main object code file and the message object code file, output to a program named program. Very good. Run the program. Success. I could have called the puts function directly from within the assembly source code. The function must be declared external, but puts like most C library functions requires passing an argument. This operation is handled in the same manner for calling assembly language functions by setting and using values in various registers. But overall, the operation, the marriage between assembly and see if you want to call it that, works as described in this movie.

Contents