Separate Compilation

If you only have one file to compile (for instance, hello.cpp), you can use:

g++ -o hello hello.cpp
However, in this lab, you will be more often working with multiple files

Let's work with an example. You can get three files by entering the commands:

cp /net/data/ftp/pub/class/170/ftp/cpp/SeparateCompile/main.cpp main.cpp
cp /net/data/ftp/pub/class/170/ftp/cpp/SeparateCompile/myFunction.cpp myFunction.cpp
cp /net/data/ftp/pub/class/170/ftp/cpp/SeparateCompile/myFunction.h myFunction.h
Note that both main.cpp and myFunction.cpp each have a reference to the .h file myFunction.h. You will have to compile each of these files separately to produce .o files and then link them all together. The following commands show how to do this. Notice the -c option you need to specify when you want to compile only, not to compile and link.

Compile only: g++ -c main.cpp
Compile only: g++ -c myFunction.cpp
Link: g++  main.o   myFunction.o  -o main
If you wanted to compile a whole set of C++ programs at the same time, you could enter: g++ -c *.cpp Be careful with this though, for these reasons:

To link a whole set of object files you could have just entered: g++   *.o   -o main Again, you should be careful that you have all your files in one directory.

The following diagram illustrates how the previous example appears conceptually: