Compiling and Linking C++ Program

When you write a C++ program, the very next step is to compile the program to generate an executable file. This process of generating executable file from a source code involves 3 main stages.

Preprocessor

The preprocessor modifies the original source code according to the directive that starts with ‘#’.

It works on one C++ source file at a time by replacing #include directives with the content of the respective files (which is usually just declarations), doing replacement of macros (#define), and selecting different portions of text depending of #if, #ifdef and #ifndef directives.

Compiler

The compiler works on the preprocessed code and translate the program into file containing the assembly code. This in turn calls the assembler that converts the assembly code to machine code(binary) as Object files. This object file contains the compiled code (in binary form) of the symbols defined in the input. Symbols in object files are referred to by name.

Object files can refer to symbols that are not defined. This is the case when you use a declaration, and don’t provide a definition for it. The compiler doesn’t mind this, and will happily produce the object file as long as the source code is well-formed.

Linker

The linker produces the final executable file by merging the object files and linking the required libraries which can be passed as an argument to the compiler.

It links all the object files by replacing the references to undefined symbols with the correct addresses. Each of these symbols can be defined in other object files or in libraries. If they are defined in libraries other than the standard library, you need to tell the linker about them.

Step by step compilation process

We can compile our c++ program using GNU c++ compiler

g++ helloapp.cpp

this creates an executable file ‘a.out’. You can run it by typing,

./a.out

To create your own executable file name, use the ‘-o’ option

g++ -o helloapp helloapp.cpp
./helloapp

Compiling multiple files

To compile multiple files, we have to compile each file separately and link them into single executable.

g++ -c hello.cpp helloapp.cpp
g++ -o myapp hello.o helloapp.cpp

Some compiler options

  • -g – turn on debugging (so GDB gives more friendly output)
  • -Wall – turns on most warnings
  • -O or -O2 – turn on optimizations
  • -o <name> – name of the output file
  • -c – output an object file (.o)
  • -I<include path> – specify an include directory
  • -L<library path> – specify a lib directory
  • -l<library> – link with library lib<library>.a

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.