Writing a Simple Operating System — from Scratch

(Jeff_L) #1

CHAPTER 5. WRITING, BUILDING, AND LOADING YOUR


KERNEL 55


$make kernel.o
which will re-compile our C source file only ifkernel.odoes not exist or has an
older file modification time thankernel.c. But it is only when we add serveral inter-
dependant rules that we see howmakecan really help us to save time and unecessary
command executions.


# Build the kernel binary
kernel.bin: kernel_entry.o kernel.o
ld -o kernel.bin -Ttext 0x1000 kernel_entry.o kernel.o --oformat binary

# Build the kernel object file
kernel.o : kernel.c
gcc -ffreestanding -c kernel.c -o kernel.o

# Build the kernel entry object file.
kernel_entry.o : kernel_entry.asm
nasm kernel_entry.asm -f elf -o kernel_entry.o

If we run make kernel.bin with the Makefile in Figure XXX,makewill know
that, before it can run the command to generatekernel.bin, it must build its two
dependencies,kernel.oandkernelentry.o, from their source files,kernel.cand
kernelentry.asm, yeilding the following output of the commands it ran:


nasm kernelentry.asm -f elf -o kernelentry.o
gcc -ffreestanding -c kernel.c -o kernel.o
ld -o kernel.bin -Ttext 0x1000 kernelentry.o kernel.o --oformat binary
Then, if we runmakeagain, we will see that make reports that the build target
kernel.binis up to date. However, if we modify, say,kernel.c, save it, then runmake
kernel.bin, we will see that only the necessary commands are run bymake, as follows:


gcc -ffreestanding -c kernel.c -o kernel.o
ld -o kernel.bin -Ttext 0x1000 kernelentry.o kernel.o --oformat binary
To reduce repetition in, and therefore improve ease of maintenance of, our Makefile,
we can use the special makefile variables$<,$@, and$^as in Figure XXX.


# $^ is substituted with all of the target ’s dependancy files
kernel.bin: kernel_entry.o kernel.o
ld -o kernel.bin -Ttext 0x1000 $^ --oformat binary

# $< is the first dependancy and $@ is the target file
kernel.o : kernel.c
gcc -ffreestanding -c $< -o $@

# Same as the above rule.
kernel_entry.o : kernel_entry.asm
nasm $< -f elf -o $@
Free download pdf