Programming in C

(Barry) #1

334 Chapter 15 Working with Larger Programs


If you’re working with a windows-based project management tool, such as
Metrowerks’ CodeWarrior, Microsoft Visual Studio, or Apple’s Xcode, then working with
multiple source files is easy.You simply have to identify the particular files that belong to
the project on which you are working, and the software handles the rest for you.The
next section describes how to work with multiple files if you’re not using such a tool,
also known as an Integrated Development Environment (IDE).That is, the next section
assumes you are compiling programs from the command line by directly issuing gccor
cccommands, for example.

Compiling Multiple Source Files from the Command Line
Suppose you have conceptually divided your program into three modules and have
entered the statements for the first module into a file called mod1.c, the statements for
the second module into a file called mod2.c, and the statements for your mainroutine
into the file main.c.To tell the system that these three modules actually belong to the
same program, you simply include the names of all three files when you enter the com-
mand to compile the program. For example, using gcc, the command
$ gcc mod1.c mod2.c main.c –o dbtest
has the effect of separately compiling the code contained in mod1.c,mod2.c, and
main.c.Errors discovered in mod1.c,mod2.c, and main.care separately identified by the
compiler. For example, if the gcccompiler gives output that looks like this:
mod2.c:10: mod2.c: In function 'foo':
mod2.c:10: error: 'i' undeclared (first use in this function)
mod2.c:10: error: (Each undeclared identifier is reported only once
mod2.c:10: error: for each function it appears in.)
then the compiler indicates that mod2.chas an error at line 10, which is in the function
foo. Because no messages are displayed for mod1.cand main.c, no errors are found
compiling those modules.
Typically, if there are errors discovered in a module, you have to edit the module to
correct the mistakes.^1 In this case, because an error was discovered only inside mod2.c,
you have to edit only this file to fix the mistake.You can then tell the C compiler to
recompile your modules after the correction has been made:
$ gcc mod1.c mod2.c main.c –o dbtest
$
Because no error message was reported, the executable was placed in the file dbtest.
Normally, the compiler generates intermediate object files for each source file that it
compiles.The compiler places the resulting object code from compiling mod.cinto the
file mod.oby default. (Most Windows compilers work similarly, only they might place

1.The error might be due to a problem with a header file included by that module, for example,
which means the header file and not the module would have to be edited.
Free download pdf