Headers and pre processing

Multiple files

Most C programs contain mutliple source files.

C programs depend on prototypes and preprocessor directive to deal with references across different files.

Prototypes

A “prototype” for a function gives its name and arguments but not its body. Allowing the caller, in any file to use that function.

For example

int Twice(int num);
void Swap(int* a, int* b);

Preprocessor

Preprocessing occurs before it is fed to the compilers.

The two most common preprocessor directives are #define and #include

#define

The #define directive allows you to make symbolioc representations with keywords.

#define MAX 100

will replace all instances of MAX in the program with 100 at compile time.

#include

Bring is text from different files during compilation. The include directive is used to pull in function prototypes found in header files.

	#include "foo.h" // Refers to a user header file

	#include <foo.h> // Refers to a system header file

Header convetions

For a file foo.c that has a collection of functions there should be

  • A separate file named foo.h, with the prototypes to the functions in foo.c
  • At the top of foo.c a #include "foo.h" directtive
  • Any xxx.c that uses foo.c must have a #include "foo.h"

#if

At compile time an if directive will allow you to select specific code to be compilled

#define FOO 1

#if FOO
	aaaa
	bbbb
#else
	bbbb
	aaaa
#endif

Assert

The assert function allows you to put various checks in a program

#include <stdio.h>
#include <assert.h>

int main()
{
    assert(2 == 3);
    printf("Hello, World!\n");
    return 0;
}

Will throw

main: main.c:6: main: Assertion `2 == 3' failed.
Written on September 15, 2017