Header file includes
- When C programs are compiled, compiler first runs separate program called preprocessor
- preprocessor operates on C program files provided and looks at preprocessor directives included
- preprocessor directive - line in C program beginning with #
- features include header file inclusion, macro expansion, conditional compilation
#include <header>
- searches for file in angled brackets and replaces include statement with file
- when angled brackets are provided, included file should be part of compiler standard library - search will be done in directory that typically stores such files (e.g.
/usr/include
)
- double quotes - search path expanded to include current source file directory
- compiler can also be provided include path for files with -I option
Macro Expansion
- Macros are defined with
#define
preprocessor directive
- object-like and function-like macros
- object-like:
#define identifier value
- identifier must not have any white space, value may
- preprocessor will search and replace each occurence of identifier with corresponding value
- common case of define directive is for defining constants, e.g.
#define MAX 10
- note that the expansion of one macro can effect a different macro
e.g:
#include <stdio.h>
#define FIRST SECOND
#define SECOND third
#define third int
FIRST main(void){
printf("Hello\\n");
}
Conditional Compilation
- Useful feature of development is to conditional suppress code segments that are irrelevant or to only compile segments that are relevant
- 6 directives for conditional compilation -
#if
, #ifdef
, #ifndef
, #elif
, #else
, #endif
- condition is evaluated by preprocessor, if condition is true, block immediately following is forwarded to compiler, suppressed if false
- e.g: compiler depend on platform
#ifdef __unix__ /* __unix__ is usually defined by compilers targeting Unix systems */
# include <unistd.h>
#elif defined _WIN32 /* _WIN32 is usually defined by compilers targeting 32 or 64 bit Windows systems */
# include <windows.h>
#endif