CSc 352 Separate Compilation Saumya Debray Dept of
CSc 352 Separate Compilation Saumya Debray Dept. of Computer Science The University of Arizona, Tucson debray@cs. arizona. edu
Issues • Types shared across multiple files • Variables used across multiple files • Functions used across multiple files • Compiling multiple files into a single executable 2
Header files • For each C source file foo. c that contains something that is used by some other file: – create a header file foo. h – foo. h contains information about stuff in foo. c that other files need to know – foo. h should be protected against multiple inclusion 3
Types shared across multiple files • Define the type as a typedef in a header file • #include the header file in every source file that needs to use that type • Each source file can then declare variables using that typedef 4
Variables used across multiple files • Declare the variable in one file • Use extern declarations for that variables elsewhere Example: file 1. c int n; extern node *list_hd; extern char buf[]; file 2. c extern int n; extern node *list_hd; char buf[256]; file 3. c extern int n; node *list_hd; extern char buf[]; 5
Functions used across multiple files • Put the prototype for the function in a header file • #include the header file in each C file that uses that function 6
Function prototypes • A construct that specifies: – the number and type of arguments for a function; and – its return type. Function definition char * foo( int x, int y, char *z[]) {. . } Function prototype char * foo( int x, int y, char *z[]); 7
Compiling multiple source files • Compile each C source file (e. g. , foo. c) into an object file (e. g. , foo. o) using gcc –c. . . • Link all of the object files into an executable using gcc: a. o : a. c gcc –Wall –c a. c –o a. o. . . gcc a. o b. o c. o -o executable 8
- Slides: 8