See this page as a slide show
User Includes
CS157 Includes
User includes
- We can divide up our code and information
into files and include them in our program.
.h
files are header files
- Define new data types
- Function prototypes (declarations)
.c
files have code, usually function definitions (bodies)
#include
#include
- Copy of a specified file included in place of the directive
#include <
filename>
- Searches official places for file
- Use for standard library files (e.g.,
stdio.h
)
#include "
filename"
- Searches current directory, then official places
- Use for user-defined files that you write
- Used for:
- Programs with multiple source files to be compiled together
- Header file—has common declarations and definitions
(classes, structures, function prototypes)
#include
// main.c
#include <stdio.h>
#include "swap.h"
void printNicely(int x, int y);
int main() {
int x = 9, y = 2;
printNicely(x, y);
swap(&x, &y);
printNicely(x, y);
return 0;
}
void printNicely(int a, int b) {
printf("(%d,%d)\n", a, b);
}
// swap.h
void swap(int *a, int *b);
// swap.c
#include "swap.h"
void swap(int *m, int *q) {
int tmp = *m;
*m = *q;
*q = tmp;
}
% c11 -c swap.c
% c11 -c main.c
% c11 main.o swap.o
Global Variables
- Global variables can be useful, but should be avoided.
- They can be modified anywhere so debugging is difficult.
- They often make code less general (using a
global variable for a head pointer to a list).
- They’re not necessary, that often.
extern
The extern
modifier tells the compiler that a
variable is defined outside of the current file.
// other.c
int flag = 10;
// main.c
extern int flag;
int main() {
return flag;
}
You probably shouldn’t need to use this (globals are bad, mmmmkay?).
Modularity: Reuse
- If a group of statements appears multiple
times in your program it should probably go into a function.
- For example, consider calculating the GPA for each record in an array
of students with a structure containing all their grades.
Modularity: Multiple Files
- Files should be used to group functions that are logically related.
- This allows this group of functions to be
reused easily in other programs (given that you didn’t use any globals).