The University of Iowa
The College of Liberal Arts and Sciences
Department of Computer Science

Programming Languages and Tools:

CS:3210:0001

Lecture/Lab #26

Programming with C++

Preprocessor, separate compilation

Preprocessor

source-1.cpp

source-2.cpp

Object file 1

Object file 2

Executable

Compilation

Linking

Preprocessor

Compiler

  • The preprocessor is executed after tokenization and before compilation

  • The result of preprocessing is a single file which is then passed to the actual compiler.

Preprocessor directives

Every preprocessor directive starts with the # character

#include <header>

#include "header"

Includes header file into current source file at the line immediately after the directive.

#define IDENTIFIER

#define IDENTIFIER replacement

#define IDENTIFIER( args ) replacement

Defines IDENTIFIER as macro, instructing the compiler to replace all successive occurrences of IDENTIFIER with its replacement (if any).

#undef IDENTIFIER

Cancels previous definition of IDENTIFIER by #define directive (if any).

#if expression / #ifdef IDENTIFIER / #ifndef IDENTIFIER

#else / #elif expression

#endif

Conditional compilation of parts of the source file.

#error error message

Shows the error message and renders the program ill-formed.

Separate compilation

point.cpp

point.hpp

point interface

point implementation

#include <point.hpp>

organism.cpp

use point

#include <point.hpp>

Ability to organize a program into a set of independent physical "modules"

Separate compilation (cont.)

  • Headers can include other headers.

  • Headers allows us to ensure that the entity declarations are the same in each file.

  • Because a header might be included more than once, we need to write headers in a way that is safe even if the header is included multiple times.

  • A .cpp file with all the header files included is called a translation unit.

  • Standard way: #include guards

  • East way: #pragma once

  • Marking a function definition as inline allows us to keep its in a header.

Programming with C++, Spring 2020, Lecture #26

By Aleksey Gurtovoy

Programming with C++, Spring 2020, Lecture #26

Preprocessor, separate compilation

  • 546