O'Reilly logo

Beginning Mac OS® X Programming by Drew McCormack, Michael Trent

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.14. Organizing Programs

As explained in Chapter 3, C programs typically comprise many source files with the extension .c. These files contain the definitions of the functions and variables that make up the program. Each source file is usually accompanied by a header file, which has the extension .h. A header file declares the parts of the source file that should be visible to the rest of the program, which may include macros, global variables, data types, and function signatures. Any .c file can utilize the declarations in a header file by including it with the #include preprocessor directive.

Take the following example: You have a function called DoSomething, and a struct called Monkey, and you want to put them into a separate file from the main function. You could write a header file, Monkey.h, which contains declarations and definitions, like this:

#ifndef MONKEY_H
#define MONKEY_H

typedef struct {
    char *name;
} Monkey;

void DoSomething(Monkey *monkey);

#endif

The first thing you will notice is that there are some preprocessor directives that don't have anything to do with the code itself. These directives are called guards. Definitions such as the struct Monkey can only be defined once, or the compiler will report an error. To avoid this, the guard is introduced, to ensure that the definitions in the header file only get imported once, no matter how many times #include "Monkey.h" appears.

The first line of the guard checks if the macro MONKEY_H is defined. If not, the preprocessor ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required