5. Separate Compilation #
Created Sunday 30 January 2022
Why separate compilation #
This is done to achieve an aspect of encapsulation: separate design and use of a class.
There are 3 kinds of files involved in the whole application:
- Interface files - the class with just member declarations. The file usually ends with a
.h
extension. - Implementation files - contains the member function definitions. File extension is
.cpp
. - Application file - contains the
main
function. FIle extension is.cpp
.
How is separate compilation done? #
It’s a 3 step procedure:
- Both the implementation and application file need to
include
the interface file. - The implementation and application files are compiled separately.
- The compiled files are then “linked” together to create the executable.
- For linking in separate compilation to be possible, both the implemenatation and application file need to
include
the interafce file. - The commands in *nix like systems are:
- Compile:
g++ -c Circle.cpp
andg++ -c App.cpp
. This generates object files namedCircle.o
andApp.o
.-c
is for compilation. - Link:
g++ -o Application Circle.o App.o
.-o
is the flag to create an executable namedApplication
, in this case. - Run the application using
./Application
.
- Compile:
What are benefits of separate compilation #
- Independedence of compiled files from the source code. That is, source code does not need to be revealed in order for the application code to be written.
- This is key for the working of proprietary software, i.e. source code remains private and only the comiled version with the interface file is made public.
- Releasing the interface file and the compiled implementation is enough for writing and compiling the application file.
- It interface file is protected from change - as the original interface is already used in compiling the implementation files, so linking can only happen with the original interface file.
- The implementation file cannot be changed because it’s very difficult to “de-compile” the implementation’s compiled version.
- For very large applications, not all files have to be compiled if there’s a change at some place. Contrast this with a single file application, one would need to recompile the whole app for any change.
The effect of 1, 2, 3 is that the whole OOP design is protected from change by the end user.
Here’s an illustration of separate compilation: