Lecture 23: Separate Compilation
Monday, April 23, 2012[Up] [Previous Lecture] [Next Lecture]
Reading Assigned: None
Homework Due: None
Homework Assigned: Homework 11 -- assigned last class
Classwork Assigned: None
Topics Covered:
- Homework 11 questions?
- Quiz 4 Topics Questions?
- Note, we will start quiz 4 at 6:00, and you have 45 minutes
- Separate Compilation
- So far all of our programs have been one file (eg. hw10.c)
- This becomes unwieldy with large programs
- C allows us to put pieces of programs into multiple .c files and compile them together
- This is very similar to our current use of libraries, where the linker combines our compiled file with the library objects
- When we provide multiple .c files to gcc, it will automatically combine them into one executable
- Example get_values.c and sep_comp_ex.c
- Example of the error when we compile just sep_comp_ex.c
linux1[1]% gcc sep_comp_ex.c /tmp/ccnrem4d.o: In function `main': sep_comp_ex.c:(.text+0x17): undefined reference to `get_int' sep_comp_ex.c:(.text+0x2d): undefined reference to `get_double' sep_comp_ex.c:(.text+0x43): undefined reference to `get_char' collect2: ld returned 1 exit status
- Example of the error when we compile just get_values.c
linux1[1]% gcc get_values.c /usr/lib/gcc/i686-redhat-linux/4.4.5/../../../crt1.o: In function `_start': (.text+0x18): undefined reference to `main' collect2: ld returned 1 exit status
- Why would get_values.c not compile on its own?
- Why would sep_comp_ex.c not compile on its own?
- Referencing functions in separate files
- In the example above I added a forward declaration to sep_comp_ex.c
- That is one method to allow compilation when relying on external functions
- The normal method is to create your own .h files
- Example of my own get_values.h file containing the forward declarations
- Example code using get_values.h sep_comp_ex2.c
- This allows you to more easily reuse code you have written
- Note that you still must ensure that the .h and .c files agree on the function signature (return type, name, and number and types of arguments)
- Also note that the way #include works, it is just like you typed in all of the file that was #included into that exact point of your code