Compiling Multiple Files: Some Theory
- We need to discuss what the compiler does to turn your code into an executable.
- We logically divide the compiler into at least three components.
- The preprocessor : prepares the files for compilation.
- The compiler proper: turns the source code into executable code
- The linker: combines (or links) multiple executable code files into a single executable.
- The preprocessor
- The preprocessor handles the preprocessor directives.
-
#include <iostream>
- It searches the standard header file locations and literally inserts this code into the file.
- This can be recursive as header files include other header files.
- Look at /usr/include/c++/9/cmath (on mirkwood)
- Look at /usr/include/math.h
- There are other preprocessor directives
- #pragma
- #define
- #ifndef - #end
-
g++ -E trinaryTest.cpp | more
- This may or may not be stored in a file.
-
- The compiler (proper)
- Takes the code produced by the preprocessor and creates object code.
- This may or may not be stored in a file.
- This may or may not be in the machine language of the target machine.
- But you can assume it is for simplicity.
-
- The linker
- Combines the object files.
- Along with system libraries
- To produce a single executable.
-
- This is how a traditional program is compiled.
- For our program we have a few more steps
- I have written a program called trinaryTest.cpp.
- It uses the code from Trinary.h/cpp
- To build this
- First compile Trinary.cpp to produce an object file Trinary.o
- To do this
- g++ -c -o Trinary.o Trinary.cpp
- Next compile trinaryTest.cpp
- g++ -o trinaryTest TrinaryTest.cpp Trinary.o
-
- You need to remember to do this every time you change any of these files.
- Make can simplify this
- Make implements the idea of a dependency.
- Some are built in or can be deduced.
- Trinary.o depends on Trinary.cpp
- trinaryTest depends trinaryTest.cpp
- Others need to be coded.
- Trinary.o also depends on Trinary.h
- trinaryTest depends on Trinary.o
- To code these we add the following lines to Makefile
- trinaryTest: Trinary.o
- Trinary.o: Trinary.h
- Make can then look at file times and deduce what needs to be recompiled.