Writing a Simple Operating System — from Scratch

(Jeff_L) #1

CHAPTER 5. WRITING, BUILDING, AND LOADING YOUR


KERNEL 60


float radius = 3.0;
float circumference = 2 * radius * 3.141592;

The pre-processor is also useful for outputing conditional code, but not conditional in
the sense that a decision is made at run-time, like with anifstatement, rather in the
sense of compile-time. For example, consider the following use of pre-processor directives
for the inclusion or exclusion of debugging code:


#ifdef DEBUG
print("Some debug message\n");
#endif

Now, if the pre-processor variableDEBUGhas been defined, such debugging code will be
included; otherwise, not. A variable may be defined on the command line when compiling
the C file as follows:


$gcc -DDEBUG -c somefile.c -o somefile.o
Such command line variable declarations are often used for compile-time configu-
ration of applications, and especially operating systems, which may include or exclude
whole sections of code, perhaps to reduce the memory footprint of the kernel on a small
embedded device.


5.4.2 Function Declarations and Header Files


When the compiler encouters a call to a function, that may or may not be defined in the
file being compiled, it may make incorrect assumptions and produce incorrect machine
code instructions if it has not yet encountered a description of the functions return type
and arguments. Recall from Section XXX that the compiler must prepare the stack for
variables that it passes to a function, but if the stack is not what the function expects,
then the stack may become corrupted. For this reason, it is important that at least a
declaration of the function’s interface, if not the entire function definition, is given before
it is used. This declaration is known as a function’sprototype.


int add(int a, int b) {
return a + b;
}

void main() {
// This is okay , because our compiler has seen the full
// definition of add.
int result = add(5, 3);

// This is not okay , since compiler does not know the return
// type or anything about the arguments.
result = divide (34.3, 12.76);

// This is not okay , because our compiler knows nothing about
Free download pdf