Multi-File Compilation
Up to now, all programs that we have written have been in a single source (i.e, .cpp) file.
When we write code for new data types, that is new structures or classes, we tend to put the code in their own separate files, so different programs can use them more easily.
However, with the new structures in separate files, we need to learn how to combine them all together into one program. Up to now when we run the compiler (g++) we have been running both the compiler and the linker without any distinction. We now make a distinction:
To only compile a program, without running the linker, use the "-c" option. For example:
g++ -c myprogram.cpp runs the compiler without the linker and produces the object (or machine code) file myprogram.o
You can join (or link) several .o files together into an executable by leaving off the -c option. For example:
g++ -o myExe mainprogram.o myprogram.o anotherprogram.o runs the compiler with the linker to combine (or link) the three object files together and puts the executable in the file myExe. Note: only one of the .o files is allowed to contain a main() function.