C++ Compilation and Linking

Taken from Monash CSSE’s 3400 Application Development with C++ webpage:

Firstly, with the normal compile and link process:
We write our programs in a file in a source language that the compiler understands (can parse). If we write code the compiler does not understand it tells us with compile error messages. If we write code that it can understand but that could have problems we get warning messages.

After the compiler has understood our code it generates machine instructions that, when executed, will do what the compiler understands we wanted the computer to do. The instructions could be native machine code or assembler (in which case the assembler is then translated (assembled) to machine code), even another programming language. The machine code often has references to data or functions in other files, such as other parts of our program or the standard libraries.

The result of compiling our source code file is an “object” file.

As already mentioned, the object files refer to other object files or libraries. Also, the various object
files and library functions must be organised into one file that the operating system can load into memory and execute. So the various object files are loaded into memory and all of the references mentioned earlier must be “fixed up” so that the actual address of the referenced data or function is used in the machine instructions. The libraries are also searched for the functions our code calls, and those functions are also loaded into the new program. Not surprisingly this process is called “linking”, and the program that does it is called the “link editor”.

If the link editor finds references but cannot find what they refer to, it reports these as errors.

The result of linking is an executable file.

OK, so where do C++ templates fit in?

When the compiler encounters a template declaration (it should be all together in a header file), it just parses it to ensure it is correct, and stores it until our code makes use of it. When we declare or define a class that uses (instantiates) it, the compiler generates the new class. This could lead to new compile errors. Then the linker will try to link our program and it may find errors too.

Leave a Reply