How C Programming Works

Don't Start from Scratch, Use Libraries

Libraries are very important in C because the C language supports only the most basic features that it needs. For example, C doesn't contain input-output (I/O) functions to read from the keyboard and write to the screen. Anything that extends beyond the basics must be written by a programmer. If the chunk of code is useful to multiple different programs, it's often put into a library to make it easily reusable.

In our discussion of C so far, we've already seen one library, the standard I/O (stdio) library. The #include line at the beginning of the program instructed the C compiler to loaded the library from its header file named stdio.h. C maintainers include standard C libraries for I/O, mathematical functions, time manipulation and common operations on certain data structures, such as a string of characters. Search the Web or your favorite C programming guide for information about the C89 standard library and the updates and additions in C99.

You, too, can write C libraries. By doing so, you can split your program into reusable modules. This modular approach not only makes it easy to include the same code in multiple programs, but it also makes for shorter program files which are easier to read, test and debug.

To use the functions within a header file, add a #include line for it at the beginning of your program. For standard libraries, put the name of the library's corresponding header file between greater-than and less-than signs (). For libraries you create yourself, put the name of the file between double quotes. Unlike statements in other parts of your C program, you don't have to put a semicolon at the end of each line. The following shows including one of each type of library:

#include <math.h>

#include "mylib.h"

A comprehensive C programming source should provide the instructions you need to write your own libraries in C. The function definitions you'll write are not any different whether they're in a library or in your main program. The difference is that you'll compile them separately in something called an object file (with a name ending in .o), and you'll create a second file, called a header file (with a name ending in .h) which contains the function prototypes corresponding to each function in the library. It's the header file you'll reference in your #include line in each main program that uses your library, and you'll include the object file as an argument in the compiler command each time you compile that program.

The C features we've explored so far are typical in other programming languages, too. Next, though, we'll talk about how C manages your computer's memory.