You are on page 1of 26

2nd Lecture: Introduction to C++ programming

Introduction
C++ is a programming language. A standardized, general-purpose, object-oriented, compiled
language. C++ is accompanied by a set of functions and containers called the C++ Standard-
Library with already built functionalities or capabilities. In 1980s, Bjarne Stroustrup created C++
as an extension to a C programming language. Still, C++ evolved to be a completely different
programming language. C++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. C++
is currently used by Adobe, Google, Microsoft, Netflix, NASA, etc.

 Let us emphasize this: C and C++ are two different languages.

C++ is widely used for the so-called systems programming as well as application programming.
C++ is a language that allows us to get down to the metal where we can perform low-level routines
if needed, or build soar high applications with abstraction mechanisms such as templates and
classes. Thus, C++ is widely considered a middle-level object-oriented programming language.

 C++ is a middle-level language rendering it the advantage of programming low-level


(drivers, kernels) and even higher-level applications (games, GUI, desktop apps etc.)

Applications of C++:
C++ finds varied usage in applications such as:
 Operating Systems & Systems Programming. e.g. Linux-based OS (Ubuntu etc.)
 Browsers (Chrome & Firefox)
 Graphics & Game engines (Photoshop, Blender, Unreal-Engine, CAD software)
 Database Engines (MySQL, MongoDB, Redis etc.)
 Cloud/Distributed Systems

C++ Integrated Development Environment (IDE)


An integrated development environment (IDE) is a software application that provides
comprehensive facilities to computer programmers for software development. Or an IDE is a
software application that helps programmers develop software code efficiently. In simple terms an
IDE is an application software for coding. It helps to code your application in less amount of time.

1|Page
@myco…TCBE 2202 Computing for Civil Engineering
An IDE typically contains a source code editor, a compiler or interpreter, build automation tools
and a debugger, accessed through a single graphical user interface (GUI). The user writes and
edits source code in the code editor. The compiler translates the source code into a readable
language that is executable for a computer.

Code or Text editor: are type of programs used to edit or write code. We will use code or text-
editors to type our C++ programs. The normal extension of a text file is (.txt) but a text file
containing C++ program should be saved with ‘.CPP’ extension. Files ending with the extension
‘.CPP’, are called source code files and they are supposed to contain source code written in C++
programming language. These extension helps the compiler to identify that the file contains a C++
program. Before beginning programming with C++, one must have a code or text-editor installed
to write programs.
C++ Compiler: Once you have installed text-editor and typed and save your program in a file
with ‘.CPP’ extension, you will need a C++ compiler to compile this file. A compiler is a
computer program which converts high-level language into machine understandable low-level
language. In other words, we can say that it converts the source code written in a programming
language into another computer language which the computer understands. For compiling a C++
program we will need a C++ compiler which will convert the source code written in C++ into
machine codes.

Debugger: A debugger or debugging tool is a computer program used to test and debug other
programs (the "target" program). The main use of a debugger is to run the target program under
controlled conditions that permit the programmer to track its execution and monitor changes in
computer resources that may indicate malfunctioning code.
Note:
 Testing is the process of finding errors in a program
 Debugging is the process of correcting errors that are found
 Bug is the error in a program e.g. Compile time errors, Runtime errors and Logical errors.
Before we start programming with C++. We will need an environment to be set-up on our local
computer to compile and run our C++ programs successfully. If you do not want to set up a local
environment you can also use online IDEs for compiling your program.

2|Page
@myco…TCBE 2202 Computing for Civil Engineering
Setting up local environment (Installing C++ IDE on Windows)
Windows Installation: There are lots of IDE available for windows operating system which you
can use to work easily with C++ programming language. One of the popular IDE is Code::Blocks.
To download Code::Blocks you may visit this link (http://www.codeblocks.org/downloads/26).
Once you have downloaded the setup file of Code::Blocks from the given link open it and follow
the instruction to install.

 After successfully installing Code::Blocks, go to File menu -> Select New and create an
Empty file.
 Now write your C++ program in this empty file and save the file with a ‘.cpp’ extension.
 After saving the file with ‘.cpp’ extension, go to Build menu and choose the Build and Run
option.

Best C++ Integrated Development Environments (IDE) and C++ Editor for Windows & Mac OS
Examples of IDEs are listed in the table below.

Name Link
Dreamweaver https://www.adobe.com/products/dreamweaver.html
Visual Studio Code https://code.visualstudio.com/
Eclipse https://www.eclipse.org/ide/
Codelite https://codelite.org/
Atom https://atom.io/
Code::Blocks http://www.codeblocks.org/downloads/26
Dev C++ https://www.bloodshed.net/
Text editor e.g. Notepad++ https://notepad-plus-plus.org/
Source: https://www.guru99.com/best-cpp-ide-editor-free.html
Note: Visual Studio Code, Codelite, Dev C++ and Code::Blocks are some of the open source
code editors (IDE) for writing programs in C++.
Code blocks Features: It is one of the best C++ IDE for Windows, Linux, and macOS that
supports GCC (GNU Compiler Collection), Visual C++, etc.

 It is one of the free C++ IDE app which provides a tabbed interface.
 This C++ editor provides one of the best C++ compiler and workspace to easily combine
more than one project.

3|Page
@myco…TCBE 2202 Computing for Civil Engineering
Basic Syntax and First Program in C++
Structure of a C++ Program and the Elements of a Program
Probably the best way to start learning a programming language is by writing a program. A C++
program basically has the following components:
• Comments
• Preprocessor Commands
• Functions
• Variables
• Statements & Expressions
If you are going to construct a building, you need two things: the construction materials e.g. bricks
and a blueprint that tells you how to put them together. In computer programming you also need
two things: data (variables) and instructions (code). Variables are the basic building blocks of a
program. Instructions tell the computer what to do with the variables.
Comments are used to describe the variables and instructions. They are notes by the author
documenting the program so it is clear and easy to read. Comments are ignored by the computer.
In construction, before we can start we must order our materials: "We need 500 large bricks, 80
half-size bricks, and 4 flagstones." Similarly, in C++ you must declare all variables before you can
use them. You must name each one of your "bricks" and tell C++ what type of "brick" to use.
After the variables are defined you can begin to use them. In construction the basic structure is a
room. By combining many rooms we form a building. In C++ the basic structure is a function.
Functions can be combined to form a program.
An apprentice builder does not start out building the Empire State Building. He starts on a one-
room house. In this chapter you will concentrate on constructing simple, one-function programs.

Basic Program Structure


The basic elements of a program are the data declarations, functions, and comments. Let's see
how these can be organized into a simple C++ program. The basic structure of a one-function
program is:
/***************************************
* Heading comments *
***************************************/
data declarations
main()
{
executable statements
return(0);
}
The heading comments tell the programmer all about the program. The data declarations describe
the data that the program is going to use.
Our single function is named main. The name main is special, because it is the first function
called. Any other functions are called directly or indirectly from main. The function main begins
with:
4|Page
@myco…TCBE 2202 Computing for Civil Engineering
main()
{
and ends with:
return(0);
}
The line return (0); is used to tell the operating system (UNIX or MSDOS/Windows) that the
program exited normally (status=0). A nonzero status indicates an error—the bigger the return
value, the more severe the error. Typically 1 is used for most simple errors, such as a missing file
or bad command-line syntax.
Now let's take a look at Our First Program and the "Hello World" program.

Our First Program


Let us create a blank text file using the text editor or C++ IDE of our choice and name it source.cpp.
First, let us create an empty C++ program that does nothing. The content of the source.cpp file is:
int main(){}
The function main is the main program entry point, the start of our program. When we run our
executable, the code inside the main function body gets executed. A function is of type int (and
returns a result to the system, but let us not worry about that just yet).
The reserved name main is a function name. It is followed by a list of parameters inside the
parentheses () followed by a function body marked with braces {}. Braces marking the beginning
and the end of a function body can also be on separate lines:
int main()
{
}
This simple program does nothing, it has no parameters listed inside parentheses, and there are no
statements inside the function body. It is essential to understand that this is the main program
signature. There is also another main function signature accepting two different parameters used
for manipulating the command line arguments. For now, we will only use the first form.

Hello World Example


Now we are ready to get the first glimpse at our “Hello World” example. The following program
is the simplest “Hello World” example. It prints out Hello World. in the console window:
Therefore, here is our first program:
// my first program in C++
#include <iostream>
int main ()
{
std::cout << "Hello World.";
return 0;
}
5|Page
@myco…TCBE 2202 Computing for Civil Engineering
The above program is the typical C++ program that programmer apprentices write for the first
time, and its result is the printing on screen of the "Hello World!" sentence. It is one of the simplest
programs that can be written in C++, but it already contains the fundamental components that
every C++ program has. Below we present the explanation of the code line by line.
1. // my first program in C++
This is a comment line. All lines beginning with two slash signs (//) are considered comments and do
not have any effect on the behavior of the program. In computer programming, a comment is a
programmer-readable explanation or annotation in the source code of a computer program. Comment
statements are not executed by the compiler and interpreter. The programmer can use them to include
short explanations or observations within the source code itself. In this case, the line is a brief
description of what our program is.

When and Why to use Comments in programming?


 A person reading a large code will be lost if comments are not provided about details of
the program.
 Comments are a way to make a code more readable by providing more descriptions.
 Comments can include a description of an algorithm to make code understandable.
 Comments can be used to prevent the execution of some parts of the code.

Types of C++ Comments


Comments are used to increase the readability of the program. There are two types of comments
in C++ based on number of lines the comment is. They are:
 Single Line Comments
 Multiple Line Comments

a) Single line comments


Single line comments in C++ start with double slashes // and the compiler ignores them. We use
them to comment or document the code or use them as notes. Examples:
int main()
{
// this is a comment
}
6|Page
@myco…TCBE 2202 Computing for Civil Engineering
We can have multiple single-line comments:
int main()
{
// this is a comment
// this is another comment
}

b) Multiple line comments.


You can also write comments that span over two or more lines. Multi-line comments start with
the /* and end with the */. They are also known as C-style comments. Example:
int main()
{
/* this is a
Multiple-line
comment */
}

Comment at End of Code Line


We can also create a comment that displays at the end of a line of code using single-line comment.
But generally, it’s better to practice putting the comment before the line of code.
Example:
// C++ program to demonstrate commenting after line of code
#include <iostream>
int main()
{
// single line comment here

std::cout <<"Welcome to KYU"; // comment here


return 0;
}

2. #include <iostream>
Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code
lines with expressions but indications for the compiler's preprocessor. In this case the directive
#include <iostream> tells the preprocessor to include the iostream standard file. This specific
file (iostream) includes the declarations of the basic standard input-output library in C++, and
it is included because its functionality is going to be used later in the program.

Note: The iostream is a header file that stands for input/output stream and provides basic
input/output services for the C++ program.
7|Page
@myco…TCBE 2202 Computing for Civil Engineering
3. int main ()
This line corresponds to the beginning of the definition of the main function. The main function is
the point by where all C++ programs start their execution, independently of its location within the
source code. It does not matter whether there are other functions with other names defined before
or after it - the instructions contained within this function's definition will always be the first ones
to be executed in any C++ program. For that same reason, it is essential that all C++ programs have
a main function.

The word main is followed in the code by a pair of parentheses (( )). That is because it is a function
declaration: In C++, what differentiates a function declaration from other types of expressions are
these parentheses that follow its name. Optionally, these parentheses may enclose a list of
parameters within them.

Right after these parentheses we can find the body of the main function enclosed in braces ({ }).
What is contained within these braces is what the function does when it is executed.

4. std::cout << "Hello World.";


This line is a C++ statement. A statement is a simple or compound expression that can actually
produce some effect. In fact, this statement performs the only action that generates a visible effect
in our first program. In this line, we have a statement to print to standard output.

cout is the name of the standard output stream in C++, and the meaning of the entire statement is
to insert a sequence of characters (in this case the Hello World sequence of characters) into the
standard output stream (cout, which usually corresponds to the screen).

cout is declared in the iostream standard file within the std namespace, so that's why we needed
to include that specific file and to declare that we were going to use this specific namespace earlier
in our code.

Notice that the statement ends with a semicolon character (;). This character is used to mark the
end of the statement and in fact it must be included at the end of all expression statements in all
C++ programs (one of the most common syntax errors is indeed to forget to include some
semicolon after a statement). Note: The ; marks the end of the statement. Statements are pieces of
the C++program that get executed. Statements end with a semicolon ; in C++.
In a nutshell, the std::cout << is the natural way of outputting data to the standard output/console
window in C++. We can output multiple string literals by separating them with multiple <<
operators: e.g.
#include <iostream>
int main()
{
std::cout << "Some string." << “Another string.";
}
8|Page
@myco…TCBE 2202 Computing for Civil Engineering
To output on a new line, we need to output a new-line character \n literal. The characters are
enclosed in single quotes '\n'. Example:
#include <iostream>
int main()
{
std::cout << "First line" << '\n' << "Second line.";
}

The \ represents an escape sequence, a mechanism to output certain special characters such as new-
line character '\n', single quote character '\'' or a double quote character '\"'. Characters can also
be part of the single string literal:
#include <iostream>
int main()
{
std::cout << "First line\nSecond line.";
}

Using namespace statement.


In C++ after the header files, we often use ‘using namespace std;’ The reason behind it is that all
of the standard library definitions are inside the namespace std. As the library functions are not
defined at global scope, so in order to use them we use namespace std. So, that we don’t need to
write std:: at every line (eg. std::cout, std::cin, etc.).

Namespaces is kind of grouping of variables under a single name. While going forward, you will
see that writing this namespace statement is useful to ease out the code.

Note: using namespace std; is used to provide standard (std) input and output namespaces. That
is, after including this statement, we do not need to write std:: before every cout and cin.
For example:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World.";
return 0;
}
9|Page
@myco…TCBE 2202 Computing for Civil Engineering
5. { and }:
The opening braces ‘{‘ indicates the beginning of the main function and the closing braces ‘}’
indicates the ending of the main function. Everything between these two comprises the body of
the main function.

6. return 0;
This is also a statement. The return statement causes the main function to finish. return may be
followed by a return code (in our example is followed by the return code with a value of zero). A
return code of 0 for the main function is generally interpreted as the program worked as expected
without any errors during its execution. This is the most usual way to end a C++ console program.
7. Indentation:
As you can see the std::cout and the return statement have been indented or moved to the right
side. This is done to make the code more readable. In a program as Hello World, it does not hold
much relevance, but as the programs become more complex, it makes the code more readable,
less error-prone. Therefore, you must always use indentations and comments to make the code
more readable.

8. Output via "cout <<"


Output in the console window

 A process return code of 0 for the main function is generally interpreted as the program
worked as expected without any errors during its execution.
 Execution time simply means time taken to execute the code.
 Press any key to close the console window. e.g. press Esc
In C++, output to the display console is done via "cout" and the stream insertion (or put-to) operator
<<. You can print as many items as you wish to cout, by chaining the items with the << operator.
For example,

cout << "hello" << " world, " << "again!" << endl;

Note: In C++, end1 - is used to insert a new line characters and flushes the stream.

10 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Basic I/O in C++
C++ IDEs comes with libraries which provides us with many ways for performing input and
output. In C++, input and output is performed in the form of a sequence of bytes or more
commonly known as streams. The two keywords cin and cout are used very often for taking
inputs and printing outputs respectively. These two are the most basic methods of taking input
and output in C++.

I/O Redirection in C++

C++ being an object-oriented programming language, gives us the ability to not only define our
own streams but also redirect standard streams. Thus, in C++, a stream is an object whose
behavior is defined by a class. Thus, anything that behaves like a stream is also a stream.
Streams Objects in C++ are mainly of three types:

 istream : Stream object of this type can only perform input operations from the stream
 ostream : These objects can only be used for output operations.
 iostream : Can be used for both input and output operations
For example:

#include <iostream>

#include: In C++, all lines that start with hash (#) sign are called directives and are processed
by a preprocessor which is a program invoked by the compiler. The #include directive tells the
compiler to include a file and #include<iostream>. It tells the compiler to include the standard
iostream file which contains declarations of all the standard input/output library functions.
Syntax:
#include< Filename >
where iostream is the name of the file to be included. The ‘<‘and ‘>’ brackets tell the compiler
to look for the file in the standard directory.

iostream:
iostream stands for standard input-output stream. This header file contains definitions of objects
like cin, cout, etc.

Basic Input / Output in C++

 Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard)
to the main memory then this process is called input.

 Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to
device (display screen) then this process is called output.
11 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Note: The two instances cout in C++ and cin in C++ of iostream class are used very often for
printing outputs and taking inputs respectively. These two are the most basic methods of taking
input and printing output in C++. To use cin and cout in C++ one must include the header
file iostream in the program.

1. Standard input stream (cin):


Usually the input device in a computer is the keyboard. C++ cin statement is the instance of the
class istream and is used to read input from the standard input device which is usually a
keyboard.
The extraction operator (>>) is used along with the object cin for reading inputs. The extraction
operator extracts the data from the object cin which is entered using the keyboard.
For example:
#include <iostream>
using namespace std;

int main()
{
int age;

cout << "Enter your age:";


cin >> age;
cout << "\nYour age is: " << age;

return 0;
}

Input:
18
Output:
Enter your age:
Your age is: 21
12 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
2. Standard output stream (cout):
Usually the standard output device is the display screen. The C++ cout statement is the instance
of the ostream class. It is used to produce output on the standard output device which is usually
the display screen. The data needed to be displayed on the screen is inserted in the standard
output stream (cout) using the insertion operator (<<).
For example:
#include <iostream>
using namespace std;
int main()
{
cout << " Am a Civil Engineer!";
return 0;
}
Output:
Am a Civil Engineer!
Example:
In the following C++ Program, we read three numbers from user, and find their sum.

13 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
More Explanation on using namespace std; in C++ program
using namespace std; Is used to provide standard (std) input and output namespaces. That is,
after including this statement, we do not need to write std:: before every cout and cin.

C++ std Namespace:


 In C++, a namespace is a collection of related names or identifiers (functions, class,
variables) which helps to separate these identifiers from similar identifiers in other
namespaces or the global namespace.
 As the same name can’t be given to multiple variables, functions, classes, etc. in the same
scope. So to overcome this situation namespace is introduced.

The identifiers of the C++ standard library are defined in a namespace called std . In order to use
any identifier belonging to the standard library, we need to specify that it belongs to
the std namespace. One way to do this is by using the scope resolution operator :: .

For example,

std::cout << "Hello World!";

Here, we have used the code std:: before cout . This tells the C++ compiler that the cout object we
are using belongs to the std namespace.

C++ std Identifiers:


All the standard library identifiers provided by the standard header files
like <iostream> , <string> , <vector> , etc. are declared in the std namespace. For example,
identifiers cin and cout are defined inside the standard header file <iostream> of the namespace std .

Utilizing std Identifiers:


We can utilize identifiers of the std namespace in our program with:
 the :: operator
 the using declaration
 the using directive
1. std Namespace Using :: Operator
The first way we access identifiers in the std namespace is by directly qualifying the identifier
with the prefix std:: . Here,
 std is the C++ standard library namespace
 :: is the scope resolution operator
14 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
For example,

#include <iostream>

int main() {

std::string first_name;

std::cout << "Enter your first name: ";


std::cin >> first_name;
std::cout << "Hello " << first_name << "!" << std::endl;
std::cout << "Welcome!";

return 0;
}
Run Code

Output

Enter your first name: Michael


Hello Michael!
Welcome!

In the above example, we are using identifiers from the std namespace directly using the scope
resolution operator ::.
Notice that we have prefixed std:: before string, cin, cout, and endl by writing:
 std::string
 std::cin
 std::cout
 std::endl
If we remove the std:: prefix from the codes above, we will get an error.

2. std Namespace with using Declaration


We can bring selected identifiers to the current scope with the help of the using declaration. To
do this, we utilize the using keyword.
By doing this, we won't need to prefix the specified identifiers with std:: .

15 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
For example,
#include <iostream>

// using declartion for cout, endl and string


using std::cout;
using std::endl;
using std::string;

int main() {

string first_name ;

cout << "Enter your first name: ";


std::cin >> first_name;
cout << "Hello " << first_name << "!" << endl;
cout << "Welcome!";

return 0;
}
Run Code

Output
Enter your first name: Ethan
Hello Ethan!
Welcome!

In the above example, we have used the using declaration for the identifiers we want to use from
the std namespace:

using std::cout;
using std::endl;
using std::string;

Here, we are telling the compiler that we want to bring only the identifiers cout , endl ,
and string from the standard namespace to the current scope. This allows us to prevent explicitly
adding prefix std:: whenever we need to access any of those identifiers.

Notice that we have used std::cin instead of cin in our program:

std::cin >> first_name;

This is because we have not included std::cin in our using declaration.


16 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
3. std Namespace with using Directive

We can use the using directive to bring all the identifiers of the namespace std as if they were
declared globally. To do this, we utilize the using keyword. By doing this, we can:
 avoid using the std:: prefix
 avoid utilizing the using declaration repeatedly

For example,

#include <iostream>

// using directive
using namespace std;

int main() {

string first_name ;

cout << "Enter your first name: ";


cin >> first_name;
cout << "Hello " << first_name << "!" << endl;
cout << "Welcome!";

return 0;
}
Run Code

Output

Enter your first name: Christine


Hello Christine!
Welcome!

In the above example, we have used the using directive to bring all the identifiers of
the std namespace to our program, including the string, cout, cin, and endl identifiers.
Notes:
 The using declaration only brings the specified identifiers of the namespace into the
current scope.
 The using directive brings all the identifiers of a namespace into the current scope.

17 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Language Translators
Overview of Compilers and interpreters
Since computers understand only machine language, it is necessary to convert the High Level
Language (HLL) programs into machine language codes. This is achieved by using language
translators or language processors, generally known as compilers, interpreters, or assemblers
that accept statements in one language and produce equivalent statements in another language.
Therefore, regardless of what language you use, you eventually need to convert your program into
machine language so that the computer can understand it. For HLL, there are two ways to do this:
 Compile the program
 Interpret the program
Difference between a compiler and an interpreter.
Note: They both covert the source code in to machine codes but;
Compiler:
A compiler stores the entire high-level program, scans it, and translates the whole program into
an equivalent machine language program. During the translation process, the compiler reads the
source program and checks the syntax (grammatical) errors (Figure ‘a’). If there is any error, it
generates an error message, which is usually displayed on the screen. In case of errors, it will not
create the object code until all the errors are rectified. Figure ‘b’ below illustrates the working of
a compiler.

Figure a: Program Translation Hierarchy Figure b: Working of a Compiler

Once the program has been compiled, the resulting machine code is saved in an executable file,
which can be run on its own at any time.
18 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Interpreter:
It is also a language translator and translates HLL into machine language. However, unlike
compilers, it translates a statement in a program and executes the statement immediately before
translating the next source language statement (Figure below). When an error is encountered in the
program, the execution of the program is halted and an error message is displayed. Similar to
compilers, every interpreted language such as BASIC and LISP has its own interpreters.

Figure: Working of an Interpreter

Assembler:
As we know, assembly language is nothing more than a symbolic representation of machine code,
which allows symbolic designation of memory locations. However, no matter how close assembly
language is to machine code, the computer still cannot understand it. Therefore, the assembly
language program must be translated into machine code by a separate program called an
assembler. The assembler program recognizes the character strings that make up the symbolic
names of the various machine operations, and substitutes the required machine code for each
instruction. At the same time, it also calculates the required address in memory for each symbolic
name of a memory location, and substitutes those addresses for the names resulting in a machine
language program that can run on its own at any time. In short, it converts the assembly codes into
binary codes and then it assembles the machine understandable code into the main memory of the
computer, making it ready for execution (Figure on next page).

19 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Figure: Working of an Assembler
Note: The original assembly language program is also known as the source code, while the final
machine language program is designated as the object code. If an assembly language program
needs to be changed or corrected, it is necessary to make the changes to the source code and then
re-assemble it to create a new object program.

Thus, the Assembler translates Low level language called assembly language (2nd Generation
language).
Linker and Loader
Linker:
An application usually consists of hundreds or thousands of lines of codes. The codes are divided
into logical groups and stored in different modules so that the debugging and maintenance of the
codes becomes easier. Hence, for an application, it is always advisable to adhere to structural
(modular) programming practices. When a program is broken into several modules, each module
can be modified and compiled independently. In such a case, these modules have to be linked
together to create a complete application. This job is done by a tool known as linker. A linker is
a program that links several object modules and libraries to form a single, coherent program
(executable). Object modules are the machine code output from an assembler or compiler and
contain executable machine code and data, together with information that allows the linker to
combine the modules together to form a program.

Generally, all HLL use some inbuilt functions like calculating square roots, finding logarithm
values, etc. These functions are usually provided by the language itself, the programmer does not
need to code them separately. During the program execution process, when a program invokes any
in-built function, the linker transfers the control to that program where the function is defined, by
making the addresses of these functions known to the calling program.

Loader:
It is a part of the operating system that brings an executable file residing on disk into the memory
and starts its execution. It is responsible for loading, linking, and relocation. In computing, a loader
is a program that performs the functions of a linker and then immediately schedules the executable
code for execution, without necessarily creating an executable file as an output. It performs the
following four basic tasks:
20 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
1. Allocation: It allocates memory space for the programs.
2. Linking: It combines two or more separate object programs and supplies the information
needed to allow references between them.
3. Relocation: It prepares a program to execute properly from its storage area.
4. Loading: It places data and machine instructions into the memory.

There are two types of loaders:


i. Absolute loader: It loads the file into the memory at the location specified by the beginning
portion (header) of the file and then passes control to the program. If the memory space specified
by the header is currently in use, execution cannot proceed, and the user must wait until the
requested memory becomes free. Moreover, this type of loader performs only loading function. It
does not perform linking and program relocation.

ii. Relocating loader: It loads the program in the memory, altering the various addresses as
required to ensure correct referencing. It is a more efficient loader, but there is a slight overhead
in terms of a small delay whilst all the relative offsets are calculated. It can only relocate code that
has been produced by a linker capable of producing relative code.

The C++ Compilation Model


We will briefly highlight key features of the C++ Compilation model in the Fig. bellow.

Figure: The C++ Compilation Model

21 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
a) The Preprocessor
The Preprocessor accepts source code as input and is responsible for
 removing comments
 Interpreting special preprocessor directives denoted by #.
For example
• #include -- includes contents of a named file. Files usually called header files. e.g.

#include <iostream.h> -- standard library I/O file


C/C++ Preprocessors:
As the name suggests, Preprocessors are programs that process our source code before
compilation. There are a number of steps involved between writing a program and executing a
program in C / C++. Let us have a look at these steps before we actually start learning about
Preprocessors.
You can see the intermediate steps in the below diagram. The source code written by
programmers is first stored in a file, let the name be “program.c“. This file is then processed by
preprocessors and an expanded source code file is generated named “program.i”. This expanded
file is compiled by the compiler and an object code file is generated named “program.obj”.
Finally, the linker links this object code file to the object code of the library functions to generate
the executable file “program.exe”.

++

Preprocessor programs provide preprocessor directives that tell the compiler to preprocess the
source code before compiling. All of these preprocessor directives begin with a ‘#’ (hash)
symbol. The ‘#’ symbol indicates that whatever statement starts with a ‘#’ will go to the
preprocessor program to get executed. Examples of some preprocessor directives
are: #include, #define, #ifndef etc. Remember that the # symbol only provides a path to the
preprocessor, and a command such as include is processed by the preprocessor program. For
example, #include will include extra code in your program. We can place these preprocessor
directives anywhere in our program.
22 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
There are 4 Main Types of Preprocessor Directives:
1. Macros:
Macros are pieces of code in a program that is given some name. Whenever this name is
encountered by the compiler, the compiler replaces the name with the actual piece of code.
The ‘#define’ directive is used to define a macro.
2. File Inclusion:
This type of preprocessor directive tells the compiler to include a file in the source code
program. There are two types of files that can be included by the user in the program:
Header files or Standard files: These files contain definitions of pre-defined functions
like cout, cin, etc.
These files must be included to work with these functions. Different functions are declared
in different header files. For example, standard I/O functions are in the ‘iostream’ file
whereas functions that perform string operations are in the ‘string’ file.
Syntax:
#include< file_name >
where file_name is the name of the file to be included. The ‘<‘ and ‘>’ brackets tell the
compiler to look for the file in the standard directory.

3. Conditional Compilation:
Conditional Compilation directives are a type of directive that helps to compile a specific
portion of the program or to skip the compilation of some specific part of the program based
on some conditions.
4. Other directives:
Apart from the above directives, there are two more directives that are not commonly
used. i.e. #undef Directive and #pragma Directive.
b) C++ Compilers
C++ programs are usually a collection of C++ code spread across one or multiple source files. The
C++ compiler compiles these files and turns them into object files. Object files are linked together
by a linker to create an executable file or a library. Some of the more popular C++ compilers are:

 The g++ frontend (as part of the GCC)


 Dev C++ or Visual C++ (as part of the Visual Studio IDE)
 Clang (as part of the LLVM)
 Intel C++
 Code Block

The C++ compiler translates source to assembly code. The source code is received from the
preprocessor.

c) Assembler
The assembler creates the object code.

23 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
d) Link Editor
If a source file references library functions or functions defined in other source files the link editor
combines these functions (with main ()) to create an executable file. External Variable references
are resolved here also.

The Basic Process of Writing a C++ Program

Step 1: Write the source codes (.cpp) and header files (.h).

Step 2: Pre-process the source codes according to the preprocessor directives. Preprocessor
directives begin with a hash sign (#), e.g., #include and #define. They indicate that
certain manipulations (such as including another file or replacement of symbols) are to
be performed BEFORE compilation.

Step 3: Compile the pre-processed source codes into object codes (.obj, .o).
A given computer understands only its own machine language. Therefore, a compiler is needed to
translate a high-level language program into an equivalent machine code. A compiler checks the
source code for syntax errors, and if there are none, then it translates each instruction into one or
more machine language instructions. The machine language version is called the object code.

Step 4: Link the compiled object codes with other object codes and the library object codes
(.lib, .a) to produce the executable code (.exe).
The object code, however, may not be ready for execution. For example, it may contain references
to other programs that a user may have written or programs that the C++ compiler provides for use
by all system users. In either case, you need a linker to resolve all these external references. The
linker finds the other programs and makes them part of your program, and so produces the
executable code

Step 5: Load the executable code into computer memory.

Step 6: Run the executable code, with the input to produce the desired output.
Once you have compiled and linked the program, you are ready to execute the program. At this
stage all you need is select the execute option from a menu. On other systems, you must execute
the program at the command level.

24 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
The figure below illustrates the basic Process of Writing a C++ Program

Important Points to Note while Writing a C++ Program (C++


Terminology and Syntax)
1. Always include the necessary header files for the smooth execution of functions. For
example, <iostream> must be included to use std::cin and std::cout.
2. The execution of code begins from the main() function.
3. It is a good practice to use Indentation and comments in programs for easy understanding.
4. cout is used to print statements and cin is used to take inputs.
5. Statement: A programming statement performs a piece of programming action. It must be
terminated by a semicolon (;) (just like an English sentence is ended with a period), as in Lines
5, and 6.
6. Preprocessor Directive: The #include (Line 2) is a preprocessor directive and NOT a
programming statement. A preprocessor directive begins with hash sign (#). It is processed
before compiling the program. A preprocessor directive is NOT terminated by a semicolon -
take note of this unusual rule.

25 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
7. Block: A block is a group of programming statements enclosed by braces { }. This group of
statements is treated as one single unit. There is one block in this program, which contains
the body of the main() function. There is no need to put a semicolon after the closing brace.
8. Comments: A multi-line comment begins with /* and ends with */, which may span more
than one line. An end-of-line comment begins with // and lasts till the end of the line.
Comments are NOT executable statements and are ignored by the compiler; but they provide
useful explanation and documentation. Use comments liberally.
9. Whitespaces: Blank, tab, and newline are collectively called whitespaces. Extra whitespaces
are ignored, i.e., only one whitespace is needed to separate the tokens. Nevertheless, extra
white spaces and newlines could help you and your readers better understand your
program. Use extra whitespaces and newlines liberally.
10. Case Sensitivity: C++ is case sensitive - a ROSE is NOT a Rose, and is NOT a rose.

26 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering

You might also like