Headers
C is completely modular. The emphasis is always on reusing existing code
by using headers to link into libraries on the system. This has the additional
benefit that your code compiles faster because the compiler does not have to
re-compile unaltered code.
Only definitions can be put into header files, another copy of this definition, complete with the statement block, must be placed into a C file as normal:
char* myfunc(int);
int anotherfunc(double);
myfunc() takes an integer value and returns a string. The code
for myfunc must exist in a .c file that is included in the main project.
anotherfunc() takes a double value as the argument and returns an integer. These
are only examples but it is already clear why you should comment your code, especially header
files, with clear, descriptive and comprehensive information on what the function does and
how it should be used. Including the C code in your project depends on your
OS, compiler and configuration. Whichever method
is used, the C code to execute myfunc() and anotherfunc() must
exist within the final program. Compilers use programs called linkers to link the relevant
code into your program by matching the definition from the header file with the definition in
the compiled C file to point to the correct statement block and it is the linker program that
provides access to all the modular components of C. If myfunc() is going to be
useful for a variety of other C projects, you can prepare it as a library file that each
project can share. This allows each project to use the code without having to compile it
themselves and means that the library can be updated for all programs at the same time.
Writing library files and writing Makefiles to use with the linker are beyond the scope of
this series.
Indenting
The Hello World sample program showed a brief example of indenting - each curly
bracket { that opens should push the following text one tab stop to the right.
Each closing curly bracket } then pushes the text back one tab stop.
int main() {
int c = 0;
for(int x=0;x<6;x++) {
// this loop will set x to 0 then 1,2,3,4 and 5 before exiting.
printf("%d",x);
c = rand();
switch(c) {
/* This is a multi-line comment.
The switch statement tests c against each case statement
and executes the code within the loop until it reaches
a break keyword.
Execution then moves to the end of the
switch statement.
*/
case 1 : {
printf("%d",c);
break;
}
default : {
break;
}
}
}
return c;
}
Comments
Single line comments start with // and end at the next newline.
Multi-line comments start with /* and only end with */.
This is part of www.codehelp.co.uk Copyright © 1998-2004 Neil Williams
See the file about.html for
copying conditions.