Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

cppProgramStructure-web

The document outlines the structure of a C++ program, emphasizing the importance of separate compilation for large projects to facilitate parallel work and faster compilation times. It details the pre-processing stage, including the use of directives like #include and #define, which modify the source code before compilation. Additionally, it discusses the organization of code into modules and the linking process that combines object files into an executable.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

cppProgramStructure-web

The document outlines the structure of a C++ program, emphasizing the importance of separate compilation for large projects to facilitate parallel work and faster compilation times. It details the pre-processing stage, including the use of directives like #include and #define, which modify the source code before compilation. Additionally, it discusses the organization of code into modules and the linking process that combines object files into an executable.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

The Structure of a C++ Program

Steven Zeil
May 25, 2013

Contents
1 Separate Compilation 2
1.1 Separate Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

2 Pre-processing 5
2.1 #include . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2 Other Pre-processing Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

3 Declarations and Definitions 13


3.1 Decls&Defs: Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.2 Decls&Defs: Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.3 Decls&Defs: Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

4 Modules 17
4.1 Coupling and Cohesion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

5 Example of Modularization: the auction program 23


5.1 Dividing Things Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.2 Possible Division . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

1
The Structure of a C++ Program

1 Separate Compilation
• C++ programs can range from a handful of statements to hundreds of thousands

• May be written by one person or by a team

Single File Programs


Putting your entire program into a single file is
• OK for small programs (CS150)

• But with large programs

– compilation would take minutes, hours, maybe days


* might break compiler
– Team members would interfere with one another’s work.
* "Are you still editing that file? You’ve had it all afternoon."
* "What do you mean you’re saving changes to the file? I’ve been editing it for the last 45 minutes!"
.............................................

Multiple File C++ Programs


By splitting a program up into multiple files that can be compiled separately,
• Team members can work in parallel on separate files

• Files are compiled separately

– each individual compilation is fast

• Separately compiled code is linked to produce the executable

– linking is much faster than compilation


.............................................

CS333 2
The Structure of a C++ Program

1.1 Separate Compilation


Separate Compilation
A.cpp B.cpp C.cpp
Source
variables: a variables: variables: b
Code functions: fa functions: fb functions: main
calls: fb(a) calls: fb(1) calls: fa(a,b), fb(a)
: fb(b)

Compiling

• Each file of source code (programming language text)


A.o B.o C.o
Object
• is compiled to produce a file of object code. Code
a: x1000 fb: x2000 b: x3000
fa: x12A0 code: fb(1) main: x3400
code: fb(x1000) code: fa(a,x3000), fb(a)

• All object code files are linked to produce the exe- : fb(x3000)

cutable Linking

foo.exe
Executable code: x2000(x1000)
: x2000(1)
: x12A0(x1000,x3000)
: x2000(x1000)
: x2000(x3000)
.............................................

Object Code

CS333 3 
The Structure of a C++ Program

A.cpp B.cpp C.cpp


Source
variables: a variables: variables: b
Code functions: fa functions: fb functions: main
calls: fb(a) calls: fb(1) calls: fa(a,b), fb(a)
: fb(b)

Compiling

• binary code, almost executable A.o B.o C.o


Object
a: x1000 fb: x2000 b: x3000
Code
• exact addresses of variables and functions not known, fa: x12A0
code: fb(x1000)
code: fb(1) main: x3400
code: fa(a,x3000), fb(a)

represented by symbols : fb(x3000)

Linking

foo.exe
Executable code: x2000(x1000)
: x2000(1)
: x12A0(x1000,x3000)
: x2000(x1000)
: x2000(x3000)
.............................................

Linking

CS333 4 
The Structure of a C++ Program

A.cpp B.cpp C.cpp


Source
variables: a variables: variables: b
Code functions: fa functions: fb functions: main
calls: fb(a) calls: fb(1) calls: fa(a,b), fb(a)
: fb(b)

Linking mainly consists of replacing symbols by real ad- Compiling


dresses.
On large projects with hundreds to thousands of files, A.o B.o C.o
Object
a: x1000 fb: x2000 b: x3000
Code
• Typically only a few files are changed on any one day fa: x12A0 code: fb(1) main: x3400
code: fb(x1000) code: fa(a,x3000), fb(a)
: fb(x3000)

• Often only the changed files need to be recompiled Linking

• Then link the changed and unchanged object code foo.exe


Executable code: x2000(x1000)
: x2000(1)
: x12A0(x1000,x3000)
: x2000(x1000)
: x2000(x3000)
.............................................

2 Pre-processing
The # Preprocessor

CS333 5 
The Structure of a C++ Program
Compilation Units Headers

A.cpp B.cpp C.cpp


#include "A.h"
Source #include "B.h" #include "A.h" A.h B.h
#include "B.h" declares: #include "B.h"
Code declares: defines: fb declares: b, main
declares: a, fa declares: fb
defines: a, fa calls: fb(1) defines: defines:
defines: b, main
calls: fb(a) calls: fa(a,b), fb(a)
: fb(b)

The preprocessor runs before the compiler proper. The pre- Pre-processing

processor:

• modifies the source code A.i B.i C.i


Translation
variables: a variables: variables: b
Units functions: fa functions: fb functions: main

• processes preprocessor instructions calls: fb(a) calls: fb(1) calls: fa(a,b), fb(a)
: fb(b)

Compiling
– lines beginning with #
A.o B.o C.o
Object
• strips out comments Code
a: x1000
fa: x12A0
fb: x2000
code: fb(1)
b: x3000
main: x3400
code: fb(x1000) code: fa(a,x3000), fb(a)
: fb(x3000)

Linking

foo.exe
Executable
code: x2000(x1000)
: x2000(1)
: x12A0(x1000,x3000)
: x2000(x1000)

.............................................
: x2000(x3000)

Pre-Processor Instructions
The common pre-processor instructions are

• #include

– insert a file

• #define

– define a macro

• #ifdef, #ifndef, #endif


– check to see if a macro has been defined

CS333 6
The Structure of a C++ Program

.............................................

2.1 #include
#include

• Inserts a file or header into the current source code

• Two versions

– #include <headerName>

* inserts a system header file from a location defined when the compiler was installed
– #include " fileName "

* inserts a file from the current directory

.............................................

Example: #include (simple case)

• Suppose we have three files:

// This is file A.h


code from A.h

//This is file B.h


#include "A.h"
code from B.h
more code from B.h

CS333 7 
The Structure of a C++ Program

//This is file C.cpp


#include "A.h"
#include "B.h"
code from C.cpp

• We ask the compiler to only run the preprocessor and save the result:
g++ −E C. cpp > C. i

• The result is file C.i

# 1 "C.cpp"
# 1 "<built-in>"
# 1 "<command line>"
# 1 "C.cpp"

# 1 "A.h" 1

code from A.h


# 3 "C.cpp" 2
# 1 "B.h" 1

# 1 "A.h" 1

code from A.h


# 3 "B.h" 2
code from B.h
more code from B.h
# 4 "C.cpp" 2
code from C.cpp

– Note the presence of content from all three files

CS333 8 
The Structure of a C++ Program

* includes markers telling where the content came from

A more realistic example

Example: #include (realistic case)


In real programs, most of the code actually seen by the compiler may come from #includes

• From this source code:

#include <iostream>

using namespace std;

int main() {
cout << "Hello World" << endl;
return 0;
}

• the compiler sees this

.............................................

Deja-Vu

CS333 9 
The Structure of a C++ Program
Compilation Units Headers

A.cpp B.cpp C.cpp


#include "A.h"
Source #include "B.h" #include "A.h" A.h B.h
#include "B.h" declares: #include "B.h"
Code declares: defines: fb declares: b, main
declares: a, fa declares: fb
defines: a, fa calls: fb(1) defines: defines:
defines: b, main
calls: fb(a) calls: fa(a,b), fb(a)
: fb(b)

Pre-processing

• Code that is in headers (.h files) may actually be com-


piled many times
A.i B.i C.i
Translation
• Code that is in compilation unit (.cpp) files will be com-Units variables: a
functions: fa
variables:
functions: fb
variables: b
functions: main
calls: fb(a) calls: fb(1) calls: fa(a,b), fb(a)

piled only once : fb(b)

Compiling

This distinction will be important later. A.o B.o C.o


Object
a: x1000 fb: x2000 b: x3000
Code fa: x12A0 code: fb(1) main: x3400
code: fb(x1000) code: fa(a,x3000), fb(a)
: fb(x3000)

Linking

foo.exe
Executable
code: x2000(x1000)
: x2000(1)
: x12A0(x1000,x3000)
: x2000(x1000)

.............................................
: x2000(x3000)

2.2 Other Pre-processing Commands


#define

• Used to define macros (symbols that the preprocessor will later substitute for)

– Sometimes used to supply constants


#define VersionNumber " 1.0 Beta1 "

i nt main ( ) {
cout << "Running version "
<< VersionNumber


<< endl ;

CS333 10
The Structure of a C++ Program

– Much more elaborate macros are possible, including ones with parameters

.............................................

#ifdef, #ifndef, #endif


Used to select code based upon whether a macro has been defined:
# i f d e f __GNUG__
/ * Compiler i s gcc / g++ * /
#endif
# i f d e f _MSC_VER
/ * Compiler i s Microsoft Visual C++ * /
#endif

.............................................

#if, #define, and #include

• All of these macros are used to reduce the amount of code seen by the actual compiler

• Suppose we have three files:

#ifndef A2_H
#define A2_H

// This is file A2.h


code from A2.h

#endif

CS333 11 
The Structure of a C++ Program

#ifndef B2_H
#define B2_H

//This is file B2.h


#include "A2.h"
code from B2.h
more code from B2.h

#endif

//This is file C.cpp


#include "A2.h"
#include "B2.h"
code from C2.cpp

• We ask the compiler to only run the preprocessor and save the result:
g++ −E C2 . cpp > C2 . i

.............................................

Shorter Translation Unit


The result is file C2.i

# 1 "C2.cpp"
# 1 "<built-in>"
# 1 "<command line>"
# 1 "C2.cpp"

CS333 12 
The Structure of a C++ Program

# 1 "A2.h" 1

code from A2.h


# 3 "C2.cpp" 2
# 1 "B2.h" 1

code from B2.h


more code from B2.h
# 4 "C2.cpp" 2
code from C2.cpp

• Note that the code from A2.h is included only once

• Imagine now, how much we would have saved if if that were iostream instead of A2.h

.............................................

3 Declarations and Definitions


Common Errors

• Some of the most common error messages are

– . . . is undeclared


– . . . is undefined

CS333 13
The Structure of a C++ Program

– . . . is defined multiple times

• Fixing these requires that you understand the difference between declarations and definitions

– and how they relate to the program structure

.............................................

Declarations
A declaration in C++

• introduces (or repeats) a name for something

• tells what “kind” of thing it is

• gives programmers enough information to use it

.............................................

Definitions
A definition in C++

• introduces (or repeats) a name for something

• tells what “kind” of thing it is

• tells what value it has and/or how it works

• gives the compiler enough information to generate this and assign it an address

.............................................

CS333 14 
The Structure of a C++ Program

General Rules for Decls & Defs

• All definitions are also declarations.

– But not vice versa

• A name must be declared before you can write any code that uses it.

• A name can be declared any number of times, as long as the declarations are identical.

• A name must be defined exactly once, somewhere within all the separately compiled files making up a program.

.............................................

3.1 Decls&Defs: Variables


Decls&Defs: Variables

• These are definitions of variables:


i nt x ;
s t r i n g s = "abc" ;
MyFavoriteDataType mfdt ( 0 ) ;

• These are declarations:


extern i n t x ;
extern s t r i n g s ;
extern MyFavoriteDataType mfdt ;

.............................................

CS333 15 
The Structure of a C++ Program

3.2 Decls&Defs: Functions


Decls&Defs: Functions

• Declaration:
i nt myFunction ( int x , int y ) ;

• Definition

i nt myFunction ( int x , int y )


{
return x + y ;
}

• The declaration provides only the header. The definition adds the body.

.............................................

3.3 Decls&Defs: Data Types


Decls&Defs: Data Types

• Data types in C++ are declared, but never defined.

• These are declarations:

typedef f l o a t Weight ;
typedef s t r i n g * S t r i n g P o i n t e r ;
enum Colors { red , blue , green } ;

• Later we will look at these type declarations

CS333 16 
The Structure of a C++ Program

str uct S { . . . } ;
class C { . . . } ;

.............................................

4 Modules
Organizing Decls & Defs into Files

• A C++ program consists of declarations and definitions.

• These are arranged into files that are combined by

– linking after separate compilation


– #include’ing one file into another

• These arrangements must satisfy the general rules:

– A name must be declared before you can write any code that uses it.
– A name can be declared any number of times, as long as the declarations are identical.
– A name must be defined exactly once, somewhere within all the separately compiled files making up a program.

.............................................

Headers and Compilation Units


A typical C++ program is divided into many source code files

• Some are headers

– Typically end in ".h"


– May be #included from many different places

CS333 17 
The Structure of a C++ Program

– May #include other headers


– Not directly compiled

• Some are compilation units

– Typically end in ".cpp", ".cc", or ".C"


– Should never be #included from elsewhere
– May #include headers
– Are directly compiled

.............................................

Can You See Me Now?...Now?...Now?


How often does the compiler process each line of code from a file?
• For headers, any number of times

• For non-headers, exactly once


Therefore a header file can only contain things that can legally appear multiple times in a C++ program – declarations
.............................................

Division: headers and non-headers

• Header files may contain only declarations

– specifically, declarations that need to be shared with different parts of the code

• Non-headers may contain declarations and definitions

– Definitions can only appear in a non-header.

• Never, ever, ever #include a non-header (.cpp) file


.............................................

CS333 18
The Structure of a C++ Program

4.1 Coupling and Cohesion


Coupling and Cohesion

• How do we divide things into different headers?

• Identify groups of declarations with

– Low coupling - dependencies on other groups


– High cohesion - dependencies within the group

.............................................

Coupling

Something with high coupling has many dependencies on ex-


ternal entities

CS333 19 
The Structure of a C++ Program

Something with low coupling has few dependencies on exter-


nal entities

.............................................

Cohesion

In something with high cohesion, all the pieces contribute to a well-defined, common goal.

CS333 20 
The Structure of a C++ Program

In something with low cohesion, the pieces have little relation to one an-
other

.............................................

Extremely Low Cohesion

CS333 21 
The Structure of a C++ Program

.............................................

Dividing into modules

• How do we divide up the non-header source files?

• Usually pair them up with a header

CS333 22 
The Structure of a C++ Program

– one non-header file for each header file


– The non-header file provide definitions for each declaration in the header that is it paired with.

• Such pairs are a one of the most common forms of module

– a group of related source code files

.............................................

5 Example of Modularization: the auction program


Read this description of the auction program. It’s an example that we will use over and over throughout the semester.

Online Auction
The overall algorithm is pretty simple
main ( fileNames [ ] ) {
readItems ;
readBidders ;
readBids ;
for each item {
resolveAuction ( item , bidders , bids )
}
}

We read in all the information about the auction, then resolve the bidding on each item, one at a time (in order by closing time
of the bidding for the items).
.............................................

The Auction Program before Modularization


We could implement that in one file:

CS333 23 
The Structure of a C++ Program

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int nItems;
const int MaxItems = 100;

// Names of items
std::string itemNames[MaxItems];

// Reserve price (minimum acceptable price)


double itemReservedPrice[MaxItems];

// Time at which auction ends for each item


int itemEndHours[MaxItems];
int itemEndMinutes[MaxItems];
int itemEndSeconds[MaxItems];

int nBidders;
const int MaxBidders = 100;

// Names of bidders
std::string bidderNames[MaxBidders];

// Account balances
double bidderBalances[MaxBidders];

CS333 24 
The Structure of a C++ Program

int nBids;
const int MaxBids = 1000;

// Names of bidders
std::string bidBidder[MaxBids];

// Bid Amounts
double bidAmounts[MaxBids];

// Names of items
std::string bidItems[MaxBids];

// Time at which bid was placed


int bidHours[MaxBids];
int bidMinutes[MaxBids];
int bidSeconds[MaxBids];

/**
* Times in this program are represented by three integers: H, M, & S,
* representing
* the hours, minutes, and seconds, respecitvely.
*/

/**
* Print a time in the format HH:MM:SS (two digits each)

CS333 25 
The Structure of a C++ Program

*/
void printTime (std::ostream& out, int h, int m, int s)
{
.
.
.
}

/**
* Compare to times. Return true iff time h1:m1:s1 is earlier than or equal to
* time time h2:m2:s2.
*
* Pre: Both times are normalized: s1, s2, m1, m2 are in the range 0..59,
* h1 and h2 are non-negative
* /
bool noLaterThan(int h1, int m1, int s1, int h2, int m2, int s2)
{
.
.
.
}

/**
* Read all bidders from the indicated file
*/
void readBidders (std::string fileName)
{
.
.
.
}

/**
* Read one item from the indicated file

CS333 26 
The Structure of a C++ Program

*/
void readItem (istream& in, int itemNum)
{
.
.
.
}

/**
* Read all items from the indicated file
*/
void readItems (std::string fileName)
{
.
.
.
}

/**
* Find the index of the bidder with the given name. If no such bidder exists,
* return nBidders.
*/
int findBidder (std::string name)
{
.
.
.
}

/**
* Read all bids from the indicated file
*/
void readBids (std::string fileName)
{

CS333 27 
The Structure of a C++ Program

.
.
.
}

/**
* Determine the winner of the auction for item #i.
* Announce the winner and remove money from winner’s account.
*/
void resolveAuction (int itemNum)
{
.
.
.
}

int main (int argc, char** argv)


{
if (argc != 4)
{
cerr << "Usage: " << argv[0] << " itemsFile biddersFile bidsFile" << endl;
return -1;
}

readItems (argv[1]);
readBidders (argv[2]);
readBids (argv[3]);

CS333 28 
The Structure of a C++ Program

for (int i = 0; i < nItems; ++i)


{
resolveAuction(i);
}
return 0;
}

. . . but it would not be a very good idea.


The details of the code for each function body really aren’t important right now (with a slight exception that I’ll get into
later). The most important thing during modularization is to know what the functions and data are and what role they play in
the program.
.............................................

A Possible Modularization
From the description of the program and from a glance through the code, we might guess that the key modules would be :1

Items Data and functions related to the items up for auction

Bidders Data and functions related to the people bidding in the auction

Bids Data and functions related to the bids placed by those people

.............................................

Module Files
And we would then expect to divide the program into files corresponding to those modules:

• Group everything describing the items into items.h and items.cpp.


1 In later lessons we’ll talk about better ways to identify good modules.

CS333 29 
The Structure of a C++ Program

• Group everything describing the bidders into bidders.h and bidders.cpp.

• Group everything describing the bids into bids.h and bids.cpp.

• Put the main program and the core auction algorithm into auctionMain.cpp.

.............................................

Making a List. . .
If we then make a list of the functions and data in this program. . .
Functions Data
Functions Data
printTime nItems
bidderBalances
noLaterThan MaxItems
nBids
readBidders itemNames
MaxBids
readItem itemReservedPrice
bidBidder
readItems itemEndHours
bidAmounts
findBidder itemEndMinutes
bidItems
readBids itemEndSeconds
bidHours
resolveAuction nBidders
bidMinutes
main MaxBidders
bidSeconds
bidderNames
.............................................

. . . and Checking It (at least twice)


. . . then we can pretty much assign these to our modules just by

• reading their names and, in a few cases,

• looking at the comments in the code that describe them:

CS333 30 
The Structure of a C++ Program

Module Functions Data


Items readItem nItems
readItems MaxItems
itemNames
itemReservedPrice
itemEndHours ..
.
itemEndMinutes
itemEndSeconds
Bidders readBidders nBidders
findBidder MaxBidders
bidderNames
bidderBalances
.............................................

Module Functions Data


Bids readBids nBids
MaxBids
bidBidder
bidAmounts
bidItems
bidHours
bidMinutes
bidSeconds
Times noLaterThan
printTime
??? resolveAuction
main

• A “times” module was introduced when we saw that two of our functions were for manipulating time values.

CS333 31 
The Structure of a C++ Program

.............................................

The “application”
The final two functions, resolveAuction and main, constitute the core algorithm, the "main application" for this particular
program, and so can be kept in the main cpp file.
.............................................
So our final division looks like:

CS333 32 
The Structure of a C++ Program

Module Functions Data


Items readItem nItems
readItems MaxItems
itemNames
itemReservedPrice
itemEndHours
itemEndMinutes
itemEndSeconds
Bidders readBidders nBidders
findBidder MaxBidders
bidderNames
bidderBalances
Bids readBids nBids
MaxBids
bidBidder
bidAmounts
bidItems
bidHours
bidMinutes
bidSeconds
Time noLaterThan
printTime
(main) resolveAuction
main

5.1 Dividing Things Up


Dividing Things Up
We can now prepare the modular version of this program.

• By default, each function or variable that we have identified gets

CS333 33 
The Structure of a C++ Program

– declared in its module’s header file and


– defined in its module’s implementation file.

.............................................

Headers are for Sharing


We can reduce possible coupling, though, by looking at the actual function bodies and

• checking to see if any of these declarations would only be used internally within a single module.

– A declaration only needs to appear in the header file if some code outside the module is using it.
– If it is only used from within its own module. it can be kept "hidden" inside that module’s .cpp file.
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int nItems;
const int MaxItems = 100;

// Names of items
std::string itemNames[MaxItems];

// Reserve price (minimum acceptable price)


double itemReservedPrice[MaxItems];

// Time at which auction ends for each item


int itemEndHours[MaxItems];

CS333 34
The Structure of a C++ Program

int itemEndMinutes[MaxItems];
int itemEndSeconds[MaxItems];

int nBidders;
const int MaxBidders = 100;

// Names of bidders
std::string bidderNames[MaxBidders];

// Account balances
double bidderBalances[MaxBidders];

int nBids;
const int MaxBids = 1000;

// Names of bidders
std::string bidBidder[MaxBids];

// Bid Amounts
double bidAmounts[MaxBids];

// Names of items
std::string bidItems[MaxBids];

// Time at which bid was placed


int bidHours[MaxBids];
int bidMinutes[MaxBids];
int bidSeconds[MaxBids];

CS333 35 
The Structure of a C++ Program

/**
* Times in this program are represented by three integers: H, M, & S,
* representing
* the hours, minutes, and seconds, respecitvely.
*/

/**
* Print a time in the format HH:MM:SS (two digits each)
*/
void printTime (std::ostream& out, int h, int m, int s)
{
if (h < 10)
out << ’0’;
out << h << ’:’;
if (m < 10)
out << ’0’;
out << m << ’:’;
if (s < 10)
out << ’0’;
out << s;
}

/**
* Compare to times. Return true iff time h1:m1:s1 is earlier than or equal to
* time time h2:m2:s2.
*
* Pre: Both times are normalized: s1, s2, m1, m2 are in the range 0..59,

CS333 36 
The Structure of a C++ Program

* h1 and h2 are non-negative


*/
bool noLaterThan(int h1, int m1, int s1, int h2, int m2, int s2)
{
// First check the hours
if (h1 > h2)
return false;
if (h1 < h2)
return true;
// If hours are the same, compare the minutes
if (m1 > m2)
return false;
if (m1 < m2)
return true;
// If hours and minutes are the same, compare the seconds
if (s1 > s2)
return false;
return true;
}

/**
* Read all bidders from the indicated file
*/
void readBidders (std::string fileName)
{
ifstream in (fileName.c_str());
in >> nBidders;
for (int i = 0; i < nBidders; ++i)
{

CS333 37 
The Structure of a C++ Program

in >> bidderNames[i] >> bidderBalances[i];


}
}

/**
* Read one item from the indicated file
*/
void readItem (istream& in, int itemNum)
{
in >> itemReservedPrice[itemNum];
in >> itemEndHours[itemNum];
char c;
in >> c; // Ignore the ’:’ between hours and minutes
in >> itemEndMinutes[itemNum];
in >> c; // Ignore the ’:’ between minutes and seconds
in >> itemEndSeconds[itemNum];

// Reading the item name.


in >> c; // Skips blanks and reads first character of the name
string line;
getline (in, line); // Read the rest of the line
itemNames[itemNum] = string(1,c) + line;
}

/**
* Read all items from the indicated file
*/
void readItems (std::string fileName)
{

CS333 38 
The Structure of a C++ Program

ifstream in (fileName.c_str());
in >> nItems;
for (int i = 0; i < nItems; ++i)
readItem (in, i);
}

/**
* Find the index of the bidder with the given name. If no such bidder exists,
* return nBidders.
*/
int findBidder (std::string name)
{
int found = nBidders;
for (int i = 0; i < nBidders && found == nBidders; ++i)
{
if (name == bidderNames[i])
found = i;
}
return found;
}

/**
* Read all bids from the indicated file
*/
void readBids (std::string fileName)
{
ifstream in (fileName.c_str());
in >> nBids;
for (int i = 0; i < nBids; ++i)

CS333 39 
The Structure of a C++ Program

{
char c;
in >> bidBidder[i] >> bidAmounts[i];
in >> bidHours[i] >> c >> bidMinutes[i] >> c >> bidSeconds[i];
string word, line;
in >> word; // First word of itemName
getline (in, line); // rest of item name
bidItems[i] = word + line;
}
}

/**
* Determine the winner of the auction for item #i.
* Announce the winner and remove money from winner’s account.
*/
void resolveAuction (int itemNum)
{
string itemName = itemNames[itemNum];
int itemH = itemEndHours[itemNum];
int itemM = itemEndMinutes[itemNum];
int itemS = itemEndSeconds[itemNum];
double itemReserve = itemReservedPrice[itemNum];

double highestBidSoFar = 0.0;


string winningBidderSoFar;
for (int bidNum = 0; bidNum < nBids; ++bidNum)
{

CS333 40 
The Structure of a C++ Program

if (noLaterThan(bidHours[bidNum], bidMinutes[bidNum], bidSeconds[bidNum],


itemH, itemM, itemS))
{
if (bidItems[bidNum] == itemName
&& bidAmounts[bidNum] > highestBidSoFar
&& bidAmounts[bidNum] > itemReserve
)
{
int bidderNum = findBidder(bidBidder[bidNum]);
// Can this bidder afford it?
if (bidAmounts[bidNum] <= bidderBalances[bidderNum])
{
highestBidSoFar = bidAmounts[bidNum];
winningBidderSoFar = bidBidder[bidNum];
}
}
}
}

// If highestBidSoFar is non-zero, we have a winner


if (highestBidSoFar > 0.0)
{
int bidderNum = findBidder(winningBidderSoFar);
cout << itemNames[itemNum]
<< " won by " << winningBidderSoFar
<< " for " << highestBidSoFar << endl;
bidderBalances[bidderNum] -= highestBidSoFar;
}
else
{
cout << itemNames[itemNum]

CS333 41 
The Structure of a C++ Program

<< " reserve not met"


<< endl;
}
}

int main (int argc, char** argv)


{
if (argc != 4)
{
cerr << "Usage: " << argv[0] << " itemsFile biddersFile bidsFile" << endl;
return -1;
}

readItems (argv[1]);
readBidders (argv[2]);
readBids (argv[3]);

for (int i = 0; i < nItems; ++i)


{
resolveAuction(i);
}
return 0;
}

CS333 42 
The Structure of a C++ Program

.............................................

Not Shared
For example, in the Items module, the function readItem, which reads a single item, is only called from inside the function
readItems, which reads an entire array of items.

• Because readItem is only called by a function within its own module, it does not need to be listed in items.h.

.............................................

5.2 Possible Division


Items

#ifndef ITEMS_H
#define ITEMS_H

#include <string>

//
// Items up for auction
//

extern int nItems;

CS333 43 
The Structure of a C++ Program

extern const int MaxItems;

// Names of items
extern std::string itemNames[];

// Reserve price (minimum acceptable price)


extern double itemReservedPrice[];

// Time at which auction ends for each item


extern int itemEndHours[];
extern int itemEndMinutes[];
extern int itemEndSeconds[];

/**
* Read all items from the indicated file
*/
void readItems (std::string fileName);

#endif

#include <iostream>
#include <fstream>

#include "items.h"

//
// Items up for auction
//

CS333 44 
The Structure of a C++ Program

using namespace std;

int nItems;

extern const int MaxItems = 100;

// Names of items
std::string itemNames[MaxItems];

// Reserve price (minimum acceptable price)


double itemReservedPrice[MaxItems];

// Time at which auction ends for each item


int itemEndHours[MaxItems];
int itemEndMinutes[MaxItems];
int itemEndSeconds[MaxItems];

/**
* Read one item from the indicated file
*/
void readItem (istream& in, int itemNum)
{
in >> itemReservedPrice[itemNum];
in >> itemEndHours[itemNum];
char c;
in >> c; // Ignore the ’:’ between hours and minutes
in >> itemEndMinutes[itemNum];
in >> c; // Ignore the ’:’ between minutes and seconds
in >> itemEndSeconds[itemNum];

CS333 45 
The Structure of a C++ Program

// Reading the item name.


in >> c; // Skips blanks and reads first character of the name
string line;
getline (in, line); // Read the rest of the line
itemNames[itemNum] = string(1,c) + line;
}

/**
* Read all items from the indicated file
*/
void readItems (std::string fileName)
{
ifstream in (fileName.c_str());
in >> nItems;
for (int i = 0; i < nItems; ++i)
readItem (in, i);
}

.............................................

Bidders

#ifndef BIDDERS_H
#define BIDDERS_H

#include <string>

//

CS333 46 
The Structure of a C++ Program

// Bidders Registered for auction


//

extern int nBidders;

extern const int MaxBidders;

// Names of bidders
extern std::string bidderNames[];

// Account balances
extern double bidderBalances[];

/**
* Read all bidders from the indicated file
*/
void readBidders (std::string fileName);

/**
* Find the index of the bidder with the given name. If no such bidder exists,
* return nBidders.
*/
int findBidder (std::string name);

#endif

CS333 47 
The Structure of a C++ Program

#include <string>
#include <fstream>
#include <iostream>
//
// Bidders Registered for auction
//

#include "bidders.h"

using namespace std;

int nBidders;

const int MaxBidders = 100;

// Names of bidders
std::string bidderNames[MaxBidders];

// Account balances
double bidderBalances[MaxBidders];

/**
* Read all bidders from the indicated file
*/
void readBidders (std::string fileName)
{
ifstream in (fileName.c_str());
in >> nBidders;
for (int i = 0; i < nBidders; ++i)

CS333 48 
The Structure of a C++ Program

{
in >> bidderNames[i] >> bidderBalances[i];
}
}

/**
* Find the index of the bidder with the given name. If no such bidder exists,
* return nBidders.
*/
int findBidder (std::string name)
{
int found = nBidders;
for (int i = 0; i < nBidders && found == nBidders; ++i)
{
if (name == bidderNames[i])
found = i;
}
return found;
}

.............................................

Bids

#ifndef BIDS_H
#define BIDS_H

#include <string>

//

CS333 49 
The Structure of a C++ Program

// Bids Received During Auction


//

extern int nBids;

extern const int MaxBids;

// Names of bidders
extern std::string bidBidder[];

// Bid Amounts
extern double bidAmounts[];

// Names of items
extern std::string bidItems[];

// Time at which bid was placed


extern int bidHours[];
extern int bidMinutes[];
extern int bidSeconds[];

/**
* Read all bids from the indicated file
*/
void readBids (std::string fileName);

CS333 50 
The Structure of a C++ Program

#endif

#include <string>
#include <fstream>

using namespace std;

//
// Bids Received During Auction
//

#include "bids.h"

int nBids;

const int MaxBids = 1000;

// Names of bidders
std::string bidBidder[MaxBids];

// Bid Amounts
double bidAmounts[MaxBids];

// Names of items
std::string bidItems[MaxBids];

// Time at which bid was placed


int bidHours[MaxBids];
int bidMinutes[MaxBids];

CS333 51 
The Structure of a C++ Program

int bidSeconds[MaxBids];

/**
* Read all bids from the indicated file
*/
void readBids (std::string fileName)
{
ifstream in (fileName.c_str());
in >> nBids;
for (int i = 0; i < nBids; ++i)
{
char c;
in >> bidBidder[i] >> bidAmounts[i];
in >> bidHours[i] >> c >> bidMinutes[i] >> c >> bidSeconds[i];
string word, line;
in >> word; // First word of itemName
getline (in, line); // rest of item name
bidItems[i] = word + line;
}
}

.............................................

Times

#ifndef TIMES_H
#define TIMES_H

CS333 52 
The Structure of a C++ Program

#include <iostream>

/**
* Times in this program are represented by three integers: H, M, & S, representing
* the hours, minutes, and seconds, respecitvely.
*/

/**
* Print a time in the format HH:MM:SS (two digits each)
*/
void printTime (std::ostream& out, int h, int m, int s);

/**
* Compare to times. Return true iff time h1:m1:s1 is earlier than or equal to
* time time h2:m2:s2.
*
* Pre: Both times are normalized: s1, s2, m1, m2 are in the range 0..59,
* h1 and h2 are non-negative
* /
bool noLaterThan(int h1, int m1, int s1, int h2, int m2, int s2);

#endif // TIMES_H

#include "times.h"

using namespace std;

/**
* Times in this program are represented by three integers: H, M, & S, representing
* the hours, minutes, and seconds, respecitvely.

CS333 53 
The Structure of a C++ Program

*/

/**
* Print a time in the format HH:MM:SS (two digits each)
*/
void printTime (std::ostream& out, int h, int m, int s)
{
if (h < 10)
out << ’0’;
out << h << ’:’;
if (m < 10)
out << ’0’;
out << m << ’:’;
if (s < 10)
out << ’0’;
out << s;
}

/**
* Compare to times. Return true iff time h1:m1:s1 is earlier than or equal to
* time time h2:m2:s2.
*
* Pre: Both times are normalized: s1, s2, m1, m2 are in the range 0..59,
* h1 and h2 are non-negative
* /
bool noLaterThan(int h1, int m1, int s1, int h2, int m2, int s2)
{
// First check the hours
if (h1 > h2)
return false;
if (h1 < h2)

CS333 54 
The Structure of a C++ Program

return true;
// If hours are the same, compare the minutes
if (m1 > m2)
return false;
if (m1 < m2)
return true;
// If hours and minutes are the same, compare the seconds
if (s1 > s2)
return false;
return true;
}

.............................................

Main Auction Program

#include <iostream>
#include <string>

using namespace std;

#include "items.h"
#include "bidders.h"
#include "bids.h"
#include "times.h"

/**
* Determine the winner of the auction for item #i.
* Announce the winner and remove money from winner’s account.
*/

CS333 55 
The Structure of a C++ Program

void resolveAuction (int itemNumber);

int main (int argc, char** argv)


{
if (argc != 4)
{
cerr << "Usage: " << argv[0] << " itemsFile biddersFile bidsFile" << endl;
return -1;
}

readItems (argv[1]);
readBidders (argv[2]);
readBids (argv[3]);

for (int i = 0; i < nItems; ++i)


{
resolveAuction(i);
}
return 0;
}

/**
* Determine the winner of the auction for item #i.
* Announce the winner and remove money from winner’s account.
*/
void resolveAuction (int itemNum)
{
string itemName = itemNames[itemNum];
int itemH = itemEndHours[itemNum];

CS333 56 
The Structure of a C++ Program

int itemM = itemEndMinutes[itemNum];


int itemS = itemEndSeconds[itemNum];
double itemReserve = itemReservedPrice[itemNum];

double highestBidSoFar = 0.0;


string winningBidderSoFar;
for (int bidNum = 0; bidNum < nBids; ++bidNum)
{
if (noLaterThan(bidHours[bidNum], bidMinutes[bidNum], bidSeconds[bidNum],
itemH, itemM, itemS))
{
if (bidItems[bidNum] == itemName
&& bidAmounts[bidNum] > highestBidSoFar
&& bidAmounts[bidNum] > itemReserve
)
{
int bidderNum = findBidder(bidBidder[bidNum]);
// Can this bidder afford it?
if (bidAmounts[bidNum] <= bidderBalances[bidderNum])
{
highestBidSoFar = bidAmounts[bidNum];
winningBidderSoFar = bidBidder[bidNum];
}
}
}
}

// If highestBidSoFar is non-zero, we have a winner


if (highestBidSoFar > 0.0)
{
int bidderNum = findBidder(winningBidderSoFar);

CS333 57 
The Structure of a C++ Program

cout << itemNames[itemNum]


<< " won by " << winningBidderSoFar
<< " for " << highestBidSoFar << endl;
bidderBalances[bidderNum] -= highestBidSoFar;
}
else
{
cout << itemNames[itemNum]
<< " reserve not met"
<< endl;
}
}

.............................................

CS333 58 

You might also like