0% found this document useful (0 votes)
54 views27 pages

Tutorial 01: How To Build A C/C++ Program?: Part 1: C Preprocessor (CPP)

The document discusses how to build C/C++ programs using source files, header files, and the C preprocessor (CPP). It explains that source files contain code and are compiled into object files, header files contain declarations and are included in source files, and CPP is used to manage code during compilation through macros, conditional compilation, and source file inclusion. The tutorial covers these topics over three parts - source and header files, CPP macros and features, and a summary.

Uploaded by

Parthapratim Das
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
54 views27 pages

Tutorial 01: How To Build A C/C++ Program?: Part 1: C Preprocessor (CPP)

The document discusses how to build C/C++ programs using source files, header files, and the C preprocessor (CPP). It explains that source files contain code and are compiled into object files, header files contain declarations and are included in source files, and CPP is used to manage code during compilation through macros, conditional compilation, and source file inclusion. The tutorial covers these topics over three parts - source and header files, CPP macros and features, and a summary.

Uploaded by

Parthapratim Das
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 27

Tutorial T01

Partha Pratim
Das

Objectives &
Programming in Modern C++
Outline
Tutorial T01: How to build a C/C++ program?: Part 1: C Preprocessor (CPP)
Source and
Header
Sample C/C++ Files

CPP
Macros
#define
Partha Pratim Das
undef
# & ##
Conditional
Department of Computer Science and Engineering
Compilation Indian Institute of Technology, Kharagpur
#ifdef
#if ppd@cse.iitkgp.ac.in
Use-Cases
Source File Inclusion
#include
#include All url’s in this module have been accessed in September, 2021 and found to be functional
Guard
#line, #error
#pragma
Standard Macros

Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.1
Tutorial Objective

Tutorial T01

Partha Pratim • How to build a C/C++ projects?


Das
• Understanding the differences and relationships between source and header files
Objectives &
Outline • How C Preprocessor (CPP) can be used to manage code during build?
Source and
Header
Sample C/C++ Files

CPP
Macros
#define
undef
# & ##
Conditional
Compilation
#ifdef
#if
Use-Cases
Source File Inclusion
#include
#include
Guard
#line, #error
#pragma
Standard Macros

Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.2
Tutorial Outline

Tutorial T01 1 Source and Header Files


Partha Pratim Sample C/C++ Files
Das
2 C Preprocessor (CPP): Managing Source Code
Objectives &
Outline Macros
Source and Manifest Constants and Macros
Header undef
Sample C/C++ Files
# & ##
CPP
Macros
Conditional Compilation
#define #ifdef
undef #if
# & ##
Conditional
Use-Cases
Compilation
#ifdef
Source File Inclusion
#if #include
Use-Cases #include Guard
Source File Inclusion
#include #line, #error
#include
Guard
#pragma
#line, #error Standard Macros
#pragma
Standard Macros 3 Tutorial Summary
Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.3
Source and Header Files

Tutorial T01

Partha Pratim
Das

Objectives &
Outline

Source and
Header
Sample C/C++ Files

CPP
Macros
#define
undef
# & ##
Conditional
Compilation
#ifdef
#if
Use-Cases
Source File Inclusion
Source and Header Files
#include
#include
Guard
#line, #error
#pragma
Standard Macros

Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.4
Source Files

Tutorial T01 • Source File: A source file is a text file on disk. It contains instructions for the
Partha Pratim
Das
computer that are written in the C / C++ programming language
◦ A source file typically has extension .c for C and .cpp for C++, though there are
Objectives &
Outline several other conventions
Source and
Header
◦ Any source file, called a Translation Unit, can be independently compiled into an
Sample C/C++ Files object file (*.o)
CPP ◦ A project may contain one or more source files
Macros
#define ◦ All object files of the project are linked together to create the executable binary file
undef
# & ##
that we run
Conditional
Compilation
◦ One of the source files must contain the main() function where the execution starts
#ifdef ◦ Every source file includes zero or more header files to reduce code duplication
#if
Use-Cases ◦ In a good source code organization, every header file has its source file that
Source File Inclusion
#include
implements functions and classes. It is called Implementation File. In addition,
#include
Guard Application Files would be there.
#line, #error
#pragma
Standard Macros

Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.5
Header Files

Tutorial T01
• Header File: A header file is a text file on disk. It contains function declarations &
Partha Pratim
Das
macro definitions (C/C++) and class & template definitions (C++) to be shared
between several source files
Objectives &
Outline ◦ A header file typically has extension .h for C and .h or .hpp for C++, though
Source and
Header
there are several other conventions (or no extension for C++ Standard Library)
Sample C/C++ Files ◦ A header file is included in one or more source or header files
CPP
◦ A header file is compiled as a part of the source file/s it is included in
Macros
#define . Precompiled header (PCH): A header file may be compiled into an intermediate form that is
undef faster to process for the compiler. Usage of PCH may significantly reduce compilation time,
# & ##
Conditional
especially when applied to large header files, header files that include many other header files,
Compilation
or header files that are included in many translation units.
#ifdef
#if
Use-Cases
◦ There are two types of header files. (More information in 19)
Source File Inclusion . Files that the programmer writes are included as #include "file"
#include . Files that comes with the compiler (Standard Library) are included as #include <file>. For
#include
Guard C++
#line, #error
#pragma
− These have no extension and are specified within std namespace
Standard Macros − The standard library files of C are prefixed with ”c” with no extension in C++
Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.6
Sample Source and Header Files in C

Tutorial T01 • Header File: fact.h: Includes the header for fact() function
Partha Pratim • Source File: fact.c: Provides the implementation of fact() function
Das • Source File: main.c: Uses fact() function to compute factorial of given values
Objectives &
Outline // File fact.h // File main.c
// Header for Factorial function // Application using Factorial function
Source and
Header #ifndef __FACT_H // Include Guard. Check #include <stdio.h> // C Std. Library Header
Sample C/C++ Files #define __FACT_H // Include Guard. Define #include "fact.h" // User Header
CPP
int fact(int); int main() {
Macros
#define
int n, f;
undef #endif // __FACT_H // Include Guard. Close
# & ## printf("Input n:"); // From stdio.h
Conditional // File fact.c scanf("%d", &n);
Compilation
// Implementation of Factorial function
#ifdef
#if
#include "fact.h" // User Header f = fact(n);
Use-Cases
Source File Inclusion int fact(int n) { printf("fact(%d) = %d", n, f); // From stdio.h
#include if (0 == n) return 1;
#include else return n * fact(n-1); return 0;
Guard
#line, #error
} }
#pragma
Standard Macros

Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.7
Sample Source and Header Files in C

Tutorial T01 • Header File: Solver.h: Includes the header for quadraticEquationSolver() function
Partha Pratim • Source File: Solver.c: Provides the implementation of quadraticEquationSolver() function
Das • Source File: main.c: Uses quadraticEquationSolver() to solve a quadratic equation
Objectives &
// File Solver.h // File main.c
Outline // User Header files // Application files
#ifndef __SOLVER_H // Include Guard. Check #include <stdio.h> // C Std. Library Header
Source and
Header #define __SOLVER_H // Include Guard. define #include "Solver.h" // User Header
Sample C/C++ Files int quadraticEquationSolver(
CPP
double, double, double, double*, double*); int main() {
#endif // __SOLVER_H // Include Guard. Close double a, b, c, r1, r2;
Macros
#define // ...
undef // File Solver.c // Invoke the solver function from Solver.h
# & ## // User Implementation files int status = quadraticEquationSolver(
Conditional #include <math.h> // C Std. Library Header a, b, c, &r1, &r2);
Compilation
#include "Solver.h" // User Header
#ifdef
#if // int printf(char *format, ...) from stdio.h
Use-Cases int quadraticEquationSolver( printf("Soln. for %dx^2+%dx+%d=0 is %d %d",
Source File Inclusion double a, double b, double c, // I/P Coeff. a, b, c, r1, r2);
#include double* r1, double* r2) { // O/P Roots // ...
#include // Uses double sqrt(double) from math.h
Guard
#line, #error
// ... return 0;
#pragma return 0; }
Standard Macros }
Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.8
Sample Source and Header Files in C++

Tutorial T01 • Header File: Solver.h: Includes the header for quadraticEquationSolver() function
Partha Pratim • Source File: Solver.cpp: Provides the implementation of quadraticEquationSolver() function
Das • Source File: main.cpp: Uses quadraticEquationSolver() to solve a quadratic equation
Objectives &
Outline // File Solver.h: User Header files // File main.c: Application file
#ifndef __SOLVER_H // Include Guard. Check #include <iostream> // C++ Std. Library Header
Source and
Header #define __SOLVER_H // Include Guard. Define using namespace std; // C++ Std. Lib. in std
Sample C/C++ Files int quadraticEquationSolver( #include "Solver.h" // User Header
double, double, double, double*, double*);
CPP
#endif // __SOLVER_H // Include Guard. Close int main() {
Macros
#define
double a, b, c, r1, r2;
undef // File Solver.cpp: User Implementation files // ...
# & ## #include <cmath> // C Std. Lib. Header in C++ // Invoke the solver function from Solver.h
Conditional using namespace std;// C++ Std. Lib. in std int status = quadraticEquationSolver(
Compilation
#include "Solver.h" // User Header a, b, c, &r1, &r2);
#ifdef
#if
Use-Cases int quadraticEquationSolver( // From iostream
Source File Inclusion double a, double b, double c, // I/P Coeff. cout<<"Soln. for "<<a<<"x^2+"<<b<<"x+"<<c"=0 is ";
#include double* r1, double* r2) { // O/P Roots cout<< r1 << r2 << endl;
#include // Uses double sqrt(double) from cmath // ...
Guard
#line, #error
// ...
#pragma return 0; return 0;
Standard Macros } }
Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.9
C Preprocessor (CPP): Managing Source Code

Tutorial T01

Partha Pratim
Das

Objectives &
Outline

Source and
Header
Sample C/C++ Files

CPP
Macros
#define
undef
# & ##
Conditional
Compilation
#ifdef
#if
Use-Cases
Source File Inclusion
C Preprocessor (CPP): Managing Source Code
#include
#include
Guard
#line, #error
#pragma Source: Preprocessor directives, cplusplus.com Accessed 13-Sep-21
Standard Macros

Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.10
C Preprocessor (CPP): Managing Source Code

Tutorial T01

Partha Pratim • The CPP is the macro preprocessor for the C and C++. CPP provides the ability for
Das
the inclusion of header files, macro expansions, conditional compilation, and line control
Objectives &
Outline • The CPP is driven by a set of directives
Source and
Header
◦ Preprocessor directives are lines included in the code of programs preceded by a #
Sample C/C++ Files ◦ These lines are not program statements but directives for the preprocessor
CPP ◦ The CPP examines the code before actual compilation of code begins and resolves
Macros
#define all these directives before any code is actually generated by regular statements
undef
# & ## ◦ The CPP directives have the following characteristics:
Conditional
Compilation
. CPP directives extend only across a single line of code
#ifdef . As soon as a newline character is found, the preprocessor directive is ends
#if
Use-Cases
. No semicolon (;) is expected at the end of a preprocessor directive
Source File Inclusion
. The only way a preprocessor directive can extend through more than one line is by preceding
#include the newline character at the end of the line by a backslash (\)
#include
Guard
#line, #error
#pragma
Standard Macros

Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.11
C Preprocessor (CPP):
Macro definitions: #define, #undef
Tutorial T01 • To define preprocessor macros we can use #define. Its syntax is:
#define identifier replacement
Partha Pratim
Das • This replaces any occurrence of identifier in the rest of the code by replacement. CPP does not
Objectives &
understand C/C++, it simply textually replaces
Outline #define TABLE_SIZE 100
Source and int table1[TABLE_SIZE];
Header int table2[TABLE_SIZE];
Sample C/C++ Files
• After CPP has replaced TABLE SIZE, the code becomes equivalent to:
CPP
Macros int table1[100];
#define int table2[100];
undef
# & ##
• We can define a symbol by -D name option from the command line. This predefines name as a macro,
Conditional
with definition 1. The following code compiles and outputs 1 when compiled with
Compilation
$ g++ Macros.cpp -D FLAG
#ifdef
#if
Use-Cases
#include <iostream> // File Macros.cpp
Source File Inclusion int main() { std::cout << (FLAG==1) << std::endl; return 0; }
#include
#include
• Note that #define is important to define constants (like size, pi, etc.), usually in a header (or
Guard beginning of a source) and use everywhere. const in a variable declaration is a better solution in
#line, #error
#pragma
C++ and C11 onward
Standard Macros

Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.12
C Preprocessor (CPP):
Macro definitions: #define, #undef
Tutorial T01 • #define can work also with parameters to define function macros:
Partha Pratim #define getmax(a,b) a>b?a:b
Das
• This replaces a occurrence of getmax followed by two arguments by the replacement expression, but
Objectives & also replacing each argument by its identifier, exactly as a function:
Outline
// function macro
Source and #include <iostream>
Header using namespace std;
Sample C/C++ Files

CPP #define getmax(a,b) ((a)>(b)?(a):(b))


Macros
#define int main() {
undef int x = 5, y;
# & ##
Conditional
y= getmax(x,2);
Compilation cout << y << endl << getmax(7,x) << endl;
#ifdef return 0;
#if }
Use-Cases
Source File Inclusion • Note that a #define function macro can make a small function efficient and usable with different
#include types of parameters. In C++, inline functions & templates achieve this functionality in a better way
#include
Guard
#line, #error
#pragma
Standard Macros

Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.13
C Preprocessor (CPP):
Macro definitions: #define, #undef
Tutorial T01

Partha Pratim
• Defined macros are not affected by block structure. A macro lasts until it is undefined with the #undef
Das preprocessor directive:
#define TABLE_SIZE 100
Objectives &
Outline int table1[TABLE_SIZE];
#undef TABLE_SIZE
Source and
Header
#define TABLE_SIZE 200
Sample C/C++ Files
int table2[TABLE_SIZE];
CPP
Macros • This would generate the same code as:
#define
undef
int table1[100];
# & ## int table2[200];
Conditional
Compilation
#ifdef • We can un-define a symbol by -U name option from the command line. This cancels any previous
#if definition of name, either built in or provided with a -D option
Use-Cases
Source File Inclusion $ g++ file.cpp -U FLAG
#include
#include
Guard • Note that #undef is primarily used to ensure that a symbol is not unknowingly being defined and
#line, #error
#pragma
used through some include path
Standard Macros

Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.14
C Preprocessor (CPP):
Macro definitions #define, #undef
Tutorial T01 • Parameterized macro definitions accept two special operators (# and ##) in the replacement sequence:
Partha Pratim The operator #, followed by a parameter name, is replaced by a string literal that contains the argument
Das passed (as if enclosed between double quotes):
Objectives & #define str(x) #x
Outline cout << str(test);
Source and
Header • This would be translated into:
Sample C/C++ Files
cout << "test";
CPP
Macros • The operator ## concatenates two arguments leaving no blank spaces between them:
#define
undef
#define glue(a,b) a ## b
# & ## glue(c,out) << "test";
Conditional
Compilation • This would also be translated into:
#ifdef
#if cout << "test";
Use-Cases
Source File Inclusion • Note that # and ## operators are primarily used in Standard Template Library (STL). They should
#include be avoided at other places. As CPP replacements happen before any C++ syntax check, macro
#include
Guard definitions can be a tricky. Code that relies heavily on complicated macros become less readable,
#line, #error since the syntax expected is on many occasions different from the normal expressions programmers
#pragma
Standard Macros expect in C++
Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.15
C Preprocessor (CPP):
Conditional Inclusions: #ifdef, #ifndef, #if, #endif, #else & #elif
Tutorial T01 • These directives allow to include or discard part of the code of a program if a certain condition is met.
Partha Pratim This is known as Conditional Inclusion or Conditional Compilation
Das • #ifdef (if defined) allows a section of a program to be compiled only if the macro that is specified as
the parameter has been #define, no matter which its value is. For example:
Objectives &
Outline #ifdef TABLE_SIZE
Source and int table[TABLE_SIZE];
Header
Sample C/C++ Files
#endif
CPP In this case, the line of code int table[TABLE SIZE]; is only compiled if TABLE SIZE was previously
Macros defined with #define, independently of its value. If it was not defined, that line will not be included in
#define
undef
the program compilation
# & ## • #ifndef (if not defined) serves for the exact opposite: the code between #ifndef and #endif directives
Conditional
Compilation
is only compiled if the specified identifier has not been previously defined. For example:
#ifdef #ifndef TABLE_SIZE
#if
Use-Cases #define TABLE_SIZE 100
Source File Inclusion #endif
#include
int table[TABLE_SIZE];
#include
Guard
#line, #error In this case, if when arriving at this piece of code, the TABLE SIZE macro has not been defined yet, it
#pragma would be defined to a value of 100. If it already existed it would keep its previous value since the
Standard Macros
#define directive would not be executed.
Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.16
C Preprocessor (CPP):
Conditional Inclusions: #ifdef, #ifndef, #if, #endif, #else & #elif
Tutorial T01
• The #if, #else and #elif (else if) directives serve • Notice how the entire structure of #if,
Partha Pratim to specify some condition to be met in order for #elif and #else chained directives ends with
Das
the portion of code they surround to be compiled. #endif
Objectives & The condition that follows #if or #elif can only • The behavior of #ifdef and #ifndef can also
Outline evaluate constant expressions, including macro ex- be achieved by using the special operators
Source and pressions. For example: defined and !defined (not defined) respec-
Header
Sample C/C++ Files #if TABLE_SIZE>200 tively in any #if or #elif directive:
CPP #undef TABLE_SIZE #if defined ARRAY_SIZE
Macros #define TABLE_SIZE 200 #define TABLE_SIZE ARRAY_SIZE
#define #elif !defined BUFFER_SIZE
undef
# & ## #elif TABLE_SIZE<50 #define TABLE_SIZE 128
Conditional
Compilation
#undef TABLE_SIZE #else
#ifdef #define TABLE_SIZE 50 #define TABLE_SIZE BUFFER_SIZE
#if #endif
Use-Cases
Source File Inclusion
#else
#include #undef TABLE_SIZE
#include
Guard
#define TABLE_SIZE 100
#line, #error #endif
#pragma
Standard Macros
int table[TABLE_SIZE];
Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.17
C Preprocessor (CPP): Typical Use-Cases
Conditional Inclusions: #ifdef, #ifndef, #if, #endif, #else & #elif
Tutorial T01
• Commenting a large chunk of code: We often need to comment a large piece of code. Doing that with
C/C++-style comment is a challenge unless the Editor provides some handy support. So we can use:
Partha Pratim #if 0 // "0" is taken as false and the codes till the #endif are excluded
Das
Code lines to comment
Objectives &
#endif
Outline • Selective debugging of code: We often need to put a lot of code the purpose of debugging which we
Source and do not want when the code is built for release with optimization. This can be managed by a DEBUG flag
Header
#ifdef _DEBUG
Sample C/C++ Files
Code for debugging like print messages
CPP #endif
Macros Then we build the code for debugging as:
#define
undef $ g++ -g -D _DEBUG file_1.cpp, file_2.cpp, ..., file_n.cpp
# & ## And we build the code for release as (-U DEBUG may be skipped if there is no built-in definition):
Conditional
Compilation
$ g++ -U _DEBUG file_1.cpp, file_2.cpp, ..., file_n.cpp
#ifdef • Controlling code from build command line: Suppose our project has support for 32-bit as well as
#if 64-bit (default) and only one has to be chosen. So we can build for 32-bit using a flag BITS32
Use-Cases
Source File Inclusion $ g++ -D _BITS32 file_1.cpp, file_2.cpp, ..., file_n.cpp
#include And code as:
#include #ifndef _BITS32
Guard
#line, #error Code for 64-bit
#pragma #else
Standard Macros Code for 32-bit
Tutorial Summary #endif
Programming in Modern C++ Partha Pratim Das T01.18
C Preprocessor (CPP):
Source File Inclusion: #include
Tutorial T01 • When the preprocessor finds an #include directive it replaces it by the entire content of the specified
Partha Pratim
header or file. There are two ways to use #include:
Das #include <header>
#include "file"
Objectives &
Outline • In the first case, a header is specified between angle-brackets <>. This is used to include headers
Source and provided by the implementation, such as the headers that compose the standard library (iostream,
Header
Sample C/C++ Files
string, ...). Whether the headers are actually files or exist in some other form is
implementation-defined, but in any case they shall be properly included with this directive.
CPP
Macros • The syntax used in the second #include uses quotes, and includes a file. The file is searched for in an
#define implementation-defined manner, which generally includes the current path. In the case that the file is
undef
# & ##
not found, the compiler interprets the directive as a header inclusion, just as if the quotes ("") were
Conditional replaced by angle-brackets (<>)
Compilation
#ifdef • We can include a file by -include file option from the command line. So
#if
using namespace std; // #include <iostream> skipped for illustration
Use-Cases
Source File Inclusion
int main() {
#include cout << "Hello World" << endl;
#include return 0;
Guard }
#line, #error
#pragma would still compile fine with:
Standard Macros
$ g++ "Hello World.cpp" -include iostream
Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.19
C Preprocessor (CPP):
Source File Inclusion: #include Guard
Tutorial T01
• Inclusions of header files may lead to the problems of Multiple Inclusion and / or Circular Inclusion
• An #include guard, sometimes called a macro guard, header guard or file guard, is a particular
Partha Pratim construct used to avoid the problem of double inclusion when dealing with the include directive
Das
• Multiple Inclusion: Consider the following files:
Objectives &
Outline
Without Guard With Guard
Source and
Header // File "grandparent.h" // File "grandparent.h"
Sample C/C++ Files struct foo { int member; }; #ifndef GRANDPARENT_H // Undefined first time
#define GRANDPARENT_H // Defined for the first time
CPP
// File "parent.h" struct foo { int member; };
Macros
#include "grandparent.h" #endif /* GRANDPARENT_H */
#define
undef
# & ## // File "child.c" // File "parent.h"
Conditional #include "grandparent.h" #ifndef PARENT_H
Compilation
#include "parent.h" #define PARENT_H
#ifdef
#include "grandparent.h"
#if
Use-Cases // Expanded "child.c": WRONG #endif /* PARENT_H */
Source File Inclusion // Duplicate definition
#include struct foo { int member; }; // File "child.c"
#include struct foo { int member; }; #include "grandparent.h"
Guard
#include "parent.h"
#line, #error
#pragma
Standard Macros // Expanded "child.c": RIGHT: Only one definition
struct foo { int member; };
Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.20
C Preprocessor (CPP):
Source File Inclusion: #include Guard
Tutorial T01
• Circular Inclusion: Consider the following files:
Partha Pratim Without Guard With Guard
Das
◦ Class Flight: Needs the info of service provider #include<iostream> // File main.h
Objectives & ◦ Class Service: Needs the info of flights it offers #include<vector>
Outline using namespace std;
#include<iostream> // File main.h
Source and #ifndef __SERVICE_H
#include<vector>
Header #define __SERVICE_H
using namespace std;
Sample C/C++ Files #include "main.h" // File Service.h
#include "main.h" // File Service.h
CPP #include "Flight.h"
#include "Flight.h"
Macros class Flight;
class Flight;
#define class Service { vector<Flight*> m_Flt; /* ... */ };
class Service { vector<Flight*> m_Flt; /* ... */ };
undef #endif // __SERVICE_H
# & ## #include "main.h" // File Flight.h
#ifndef __FLIGHT_H
Conditional #include "Service.h"
Compilation #define __FLIGHT_H
class Service;
#ifdef #include "main.h" // File Flight.h
class Flight { Service* m_pServ; /* ... */ };
#if #include "Service.h"
#include "main.h" // File main.cpp
Use-Cases class Service;
#include "Service.h"
Source File Inclusion class Flight { Service* m_pServ; /* ... */ };
#include #include "Flight.h"
#endif // __FLIGHT_H
#include int main() { /* ... */ return 0; };
Guard #include "main.h" // File main.cpp
#line, #error ◦ Class Flight and Class Service has cross-references #include "Service.h"
#pragma ◦ Hence, circular inclusion of header files lead to infinite #include "Flight.h"
Standard Macros loop during compilation int main() { /* ... */ return 0; };
Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.21
C Preprocessor (CPP):
Line control: #line and Error directive #error
Tutorial T01 • When we compile a program and some error happens during the compiling process, the compiler shows
Partha Pratim an error message with references to the name of the file where the error happened and a line number,
Das so it is easier to find the code generating the error.
Objectives &
• #line directive allows us to control both things, the line numbers within the code files as well as the file
Outline name that we want that appears when an error takes place. Its format is:
Source and #line number "filename"
Header
Sample C/C++ Files
Where number is the new line number that will be assigned to the next code line. The line numbers of
CPP
successive lines will be increased one by one from this point on.
Macros "filename" is an optional parameter that allows to redefine the file name that will be shown. For
#define example:
undef
# & ## #line 20 "assigning variable"
Conditional int a?;
Compilation
#ifdef This code will generate an error that will be shown as error in file "assigning variable", line 20
#if • #error directive aborts the compilation process when it is found, generating a compilation error that
Use-Cases
Source File Inclusion
can be specified as its parameter:
#include #ifndef __cplusplus
#include #error A C++ compiler is required!
Guard
#line, #error #endif
#pragma
Standard Macros
This example aborts the compilation process if the macro name cplusplus is not defined (this macro
name is defined by default in all C++ compilers).
Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.22
C Preprocessor (CPP):
Pragma directive: #pragma
Tutorial T01 • This directive is used to specify diverse options to the compiler. These options are specific for the
Partha Pratim platform and the compiler you use. Consult the manual or the reference of your compiler for more
Das information on the possible parameters that you can define with #pragma
Objectives &
• If the compiler does not support a specific argument for #pragma, it is ignored - no syntax error is
Outline generated
Source and • Many compilers, including GCC, supports #pragma once which can be used as #include guard. So
Header
#ifndef __FLIGHT_H
Sample C/C++ Files
#define __FLIGHT_H
CPP #include "main.h" // File Flight.h
Macros #include "Service.h"
#define class Service;
undef
class Flight { Service* m_pServ; /* ... */ };
# & ##
Conditional
#endif // __FLIGHT_H
Compilation
#ifdef can also be written as:
#if
Use-Cases
#pragma once
Source File Inclusion
#include "main.h" // File Flight.h
#include #include "Service.h"
#include class Service;
Guard
class Flight { Service* m_pServ; /* ... */ };
#line, #error
#pragma
Standard Macros
This is cleaner, but may have portability issue across machines and compilers
Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.23
C Preprocessor (CPP):
Predefined Macro Names
Tutorial T01 • The following macro names are always defined (they begin and end with two underscore characters, ):
Partha Pratim Macro Value
Das
LINE Integer value representing the current line in the source code file being
Objectives & compiled
Outline
FILE A string literal containing the presumed name of the source file being
Source and compiled
Header
Sample C/C++ Files
DATE A string literal in the form “Mmm dd yyyy” containing the date in which
CPP
the compilation process began
Macros TIME A string literal in the form “hh:mm:ss” containing the time at which the
#define compilation process began
undef
# & ## cplusplus An integer value. All C++ compilers have this constant defined to some
Conditional value. Its value depends on the version of the standard supported by the
Compilation
#ifdef
compiler:
#if • 199711L: ISO C++ 1998/2003
Use-Cases
• 201103L: ISO C++ 2011
Source File Inclusion
#include Non conforming compilers define this constant as some value at most
#include five digits long. Note that many compilers are not fully conforming and
Guard
#line, #error thus will have this constant defined as neither of the values above
#pragma STDC HOSTED 1 if the implementation is a hosted implementation (with all standard
Standard Macros
headers available) 0 otherwise
Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.24
C Preprocessor (CPP):
Predefined Macro Names
Tutorial T01 • The following macros are optionally defined, generally depending on whether a feature is available:
Partha Pratim Macro Value
Das
STDC In C: if defined to 1, the implementation conforms
Objectives & to the C standard.
Outline In C++: Implementation defined
Source and STDC VERSION In C:
Header
Sample C/C++ Files
• 199401L: ISO C 1990, Ammendment 1
• 199901L: ISO C 1999
CPP
Macros
• 201112L: ISO C 2011
#define In C++: Implementation defined
undef
# & ##
STDC MB MIGHT NEQ WC 1 if multibyte encoding might give a character a
Conditional different value in character literals
Compilation
#ifdef
STDC ISO 10646 A value in the form yyyymmL, specifying the date
#if of the Unicode standard followed by the encoding
Use-Cases
of wchar t characters
Source File Inclusion
#include
STDCPP STRICT POINTER SAFETY 1 if the implementation has strict pointer safety
#include (see get pointer safety)
Guard
#line, #error STDCPP THREADS 1 if the program can have more than one thread
#pragma
Standard Macros
• Macros marked in blue are frequently used
Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.25
C Preprocessor (CPP): Standard Macro Examples

Tutorial T01 • Consider:


Partha Pratim // standard macro names
Das #include <iostream>
using namespace std;
Objectives &
Outline
int main()
Source and {
Header cout << "This is the line number " << __LINE__;
Sample C/C++ Files
cout << " of file " << __FILE__ << ".\n";
CPP cout << "Its compilation began " << __DATE__;
Macros cout << " at " << __TIME__ << ".\n";
#define cout << "The compiler gives a __cplusplus value of " << __cplusplus;
undef return 0;
# & ##
}
Conditional
Compilation
#ifdef
#if
• The output is:
Use-Cases This is the line number 7 of file Macros.c.
Source File Inclusion Its compilation began Sep 13 2021 at 11:30:07.
#include The compiler gives a __cplusplus value of 201402
#include
Guard
#line, #error
#pragma
• Note that LINE , FILE , DATE , and TIME important for details in error reporting
Standard Macros

Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.26
Tutorial Summary

Tutorial T01

Partha Pratim • Understood the differences and relationships between source and header files
Das
• Understood how CPP can be harnessed to manage code during build
Objectives &
Outline

Source and
Header
Sample C/C++ Files

CPP
Macros
#define
undef
# & ##
Conditional
Compilation
#ifdef
#if
Use-Cases
Source File Inclusion
#include
#include
Guard
#line, #error
#pragma
Standard Macros

Tutorial Summary
Programming in Modern C++ Partha Pratim Das T01.27

You might also like