Classwork 12: Separate Compilation


To practice compiling a program from parts in separate files.


Your assignment is to implement some simple functions in a separate file and compile your functions with a main program. You are not given access to the C source code of the main program. You only have the object file: story.o. (You should download this file and save it in the directory for this classwork.)

The combined program prints out a silly story. It uses the functions that you supply to fill in the blanks. The function prototypes of the functions that you must implement are in the file parts.h. You should download this file and save it in the same directory as for the main program, but do not edit this file.

Here are the function prototypes of the functions you must implement:

#ifndef _PARTS_H #define _PARTS_H void animal1() ; void animal2() ; void adjective1() ; void adjective2() ; void adjective3() ; void game() ; void vehicle() ; #endif

Each of these functions simply prints out a single word or phrase that corresponds to the topic or part of speech. (Yes, these are very simple functions --- no parameters or return values.)

Step 1:

Create a new file called parts1.c
This must be a new file. Do not edit your parts.h file.

Step 2: In a file named parts1.c implement all the functions listed above. Each function is only one printf statement. For example, the implementation of adjective3() might be:

void adjective3() {
   printf("esoteric") ;

Note that you should not have a main function in this file!

When you are done, compile the file using gcc and the -c option:

PT[195]% gcc -Wall -c parts1.c

Use the Unix ls command to list the files in your current directory. There should be a file named parts1.o. Now you can combine your functions with the main program in story.o.

PT[196]% gcc parts1.o story.o -o story1.out

The -o option here renames the executable program (Without the option, the default is a.out.) Now you can run the program and read your story:

PT[197]% ./story1.out

Step 3:

Make a copy of parts1.c and name it parts2.c. Now that you have read the story, you can be more careful in your choice of words. Change the functions in parts2.c to make the resulting story as funny as you can make it. (Limit the output of each function to one word or one phrase.)

Now you can compile and run the second version of your story:

PT[198]% gcc -c parts2.c
PT[201]% gcc parts2.o story.o -o story2.out
PT[202]% ./story2.out 

Notice that you did not need to (and couldn't without the source code) recompile the main program in story.o.


Use the script command to record yourself compiling and running both versions the program. Please do not use a text editor while you are in the script command. Submit your C source code and the typescript file as usual:

submit cs104_chang cw12 parts1.c parts2.c parts.h typescript

You do not need to (and should not) submit story.o.