Tutorial 8 (Nov 16): Separate compilation, invoking assembly from C, invoking C from assembly
Separate Compilation
There are several reasons why you may want to split a program into multiple parts:
- split a large project into manageable pieces
- write reusable code/libraries, or use other people's code/libraries
- invoke C code from assembly
- invoke assembly code from C
To turn everything into a single program, we need to compile each module (.c or .s) into relocatable object code (.o files). We then need to link the .o files together.
To compile/assemble file1.c to file1.o, we use the -c flag with gcc: gcc file1.c -c
To compile/assemble file2.s to file2.o, we use the -s flag with as: as file2.s -o file2.o
To link all the .o files, use gcc: gcc file1.o file2.o -o execFile
Then run the executable like usual: ./execFile
Makefile
While you write and test your program, you will have to repeat the above process many times. To automate the process, we can write a makefile. Once you have a makefile, you can simply use the make command to build your project.
For A5, you can use the following makefile: [makefile][114B]
To use: put the makefile in the same directory as a5aMain.c and a5a.asm, then just enter make
Note that you must name your files as specified in the assignment: a5aMain.c and a5a.asm
Even if you don't use macros, please name it a5a.asm instead of a5a.s.
all: a5aMain.o a5a.o
gcc -o a5a a5aMain.o a5a.o
a5aMain.o: a5aMain.c
gcc -c a5aMain.c
a5a.o: a5a.asm
m4 a5a.asm > a5a.s
as a5a.s -o a5a.o
There are three rules here. The first one, "all", is the default one run by make. It specifies the dependencies (or requirements), in this case a5aMain.o and a5a.o. If the requirements are met, it will link the files together and create the a5a executable.
The second rule is the rule for a5aMain.o, in case it doesn't exist yet. If it doesn't exist, it will look for a5aMain.c, and compile a .o file.
The third rule is the rule for a5a.o. If it doesn't exist, make will look for a5a.asm, run it through m4, then convert the resulting .s file to a .o file.
Invoking assembly code from C code
Full credits to Prof. Manzara. I thought of new examples, but these ones are super simple to understand. | |
main.c | sum.s |
|
|
To compile and execute:gcc -c main.c as sum.s -o sum.o gcc main.o sum.o -o myprog OR gcc *.o -o myprog (IF you want to include all .o files) |
Invoking C code from assembly code
Full credits to Prof. Manzara. I thought of new examples, but these ones are super simple to understand. | |
main.s | sum.c |
|
|
To compile and execute:gcc -c sum.c as main.s -o main.o gcc main.o sum.o -o myprog OR gcc *.o -o myprog (IF you want to include all .o files) |