Sie sind auf Seite 1von 10

Laboratory Module 1

C Compilation Model

Purpose:
To highlight key features of the C Compilation model
To review C keywords and C Standard Library functions
To understand the flexibility of the translation processes, introduced by the options
that can be invoked at compilation time
To see the usage of compilation directives

1 Preparation Before Lab

1.1 Theoretical aspects

1.1.1 Preparing programs for execution
Preparing programs for execution requires three main steps:
1) Problem specification
The main goal of this step is to specify exactly what the problem is and what the requirements for
an acceptable solution. The problem specification must be precise, so it removes all ambiguity; complete,
to consider all possibilities for input and specify the associated output; understandable, so that both the
user and the system analyst must be able to understand the problem.
Example: The computation of the sum of the first 1000 positive integers.

2) Design
At this step, the algorithms that solves the problem needs to be written in pseudocode. This is a
high-level, non-executable notation for design description. The characteristics of pseudocode are:
has a free syntax
uses a limited number of reserved words (keywords) each expressing:
- an elementary action
- a control structure
Example: The pseudocode of the problem is:
no<-0
sum<-0
while no<1000 do
sum<-sum+no
no<-no+1
end while
write(sum of first 1000 no-s=,sum)

3) Creating the program
At this step, a file containing the complete program must be created. Any editor may be used to
create the file. The source code for the above problem is presented as the second example in this laboratory.

1.1.2 The Preprocessor / C Compiler / Assembler / Link Editor / Using Libraries

After the source file is created, it cannot be immediately run, or executed. Source code must be
translated from its human-readable form into a binary version called object code, or machine code, that is
understood by the host computer. This is accomplished either by an interpreter or a compiler.
Interpreters read and convert source code one line at a time and execute it directly. Compilers read
and convert the entire program into object code without executing it, creating a separate file called an
object file. Theoretically, any language's source code can be interpreted or compiled. Although C
interpreters have had popularity as debugging tools, C source files are usually compiled. A compiled
program generally executes faster than an interpreted program.
Preprocessing and Compiling
The compiler carries out both preprocessing and compiling. Preprocessing is the modification of a
source file prior to its translation into machine language, through the execution of any preprocessing
directives that the programmer has embedded in the source code. Preprocessing is carried out by a part of
the compiler (actually a separate program) called a preprocessor. An example of preprocessing is the
addition of header files to a source file through the execution of include statements.
Once preprocessed, the source file is then compiled, or translated into a version of the program
called an object file. Object files are given a default extension, such as .o or .obj, by the compiler.
The preprocessor accepts source code as input and is responsible for removing comments and
interpreting special preprocessor directives denoted by #. All preprocessor directives or commands begin
with a #.
For example:
* #include - includes contents of a named file. Files usually called header files. e.g
#include <math.h> //standard library maths file.
#include <stdio.h> //standard library I/O file
* #define - defines a symbolic name or constant. Macro substitution.
#define MAX_ARRAY_SIZE 100


Figure 1. C Compilation Model


Linking
Owing to the modular approach of C, the final components of a C program most likely will be
contained in separate places. Before the final program can be run, all the different modules must be
connected, or linked together. This process of linking is accomplished by a program called a linker.
Two types of modules might need to be linked to an object file to create a final, executable
program:
1) Library functions exist in programmer libraries and are already compiled into object code. Although
header files containing information about library functions are added to a source file, the functions
themselves are not. Linking connects an object file with the addresses of any library functions called
within the program.
2) Other object files. For large programs that are built from separate source files, linking provides the
mechanism to connect a recently compiled object file with previously compiled files to produce a
complete program.
The steps of preprocessing, compiling, and linking are often referred to as the build process. The
build process culminates in a build of the program, or a final, executable version.
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
resolved here also.
C is an extremely small language. Many of the functions of other languages are not included in C.
e.g. No built in I/O, string handling or math functions. C provides functionality through a rich set function
libraries. As a result most C implementations include standard libraries of functions for many facilities (I/O
etc.). For many practical purposes these may be regarded as being part of C. But they may vary from
machine to machine. (e.g. TurboC to UNIX). Appendix gives further details on the standard libraries of C.
A programmer can also develop his or her own function libraries and also include special purpose libraries.
Executing
Executing a program is the act of running the final version of the program provided by the linker.
To execute a C program, the program name must be entered at the operating-system prompt.
Debugging a C Program
In the development of a C program, errors can occur either during compilation (or compile time),
during linking (or link time), or during execution (or run time).
Compile-Time Errors
Errors reported by the compiler are generally syntax errors where an element of the source code
isn't in a format that can be converted to valid C object code. When the compiler reports an error, it gives a
number indicating the line in the source file that generated the error followed by an error code and a brief
description of the error.
Common causes of compiler errors are:
1) a missing semi-colon following a C statement,
2) improperly spelled keywords, and
3) improperly delimited code blocks involving either too few or too many braces.
Link-Time Errors
Link-time errors are the result of problems the linker has in connecting an object file with external
modules needed to run the program. Like the compiler, when the linker reports an error, it provides an error
code and a brief error description. However, because the linker works with object files output by the
compiler, it does not provide a number of a line in the source file for you to refer to when you're
troubleshooting.
Common causes of linker errors are:
1) In the source file, either with misspelled names of external functions or with a missing reference to an
appropriate header file.
2) At the command line, either with mistyped names of other object files or with a mistyped library name.
Run-Time Errors
Run-time errors occur during the actual execution of a program, causing a program to operate in
unexpected ways. Rather than the result of a syntax problem, they're conceptual in nature and are also
called logic or semantic errors.

1.1.3 C keywords

break This statement allows the program to escape from for, while, do ... while loops and switch
structures.
It should NOT be used to escape from an if block.
switch-case The switch-case statement is a multi-way decision statement. Unlike the multiple decision
statement that can be created using if-else, the switch statement evaluates the conditional
expression and tests it against numerous constant values. The branch corresponding to the
value that the expression matches is taken during execution.
The value of the expressions in a switch-case statement must be an ordinal type i.e.
integer, char, short, long, etc. Float and double are not allowed.
char char defines characters
double double is used to define big floating point numbers. It reserves twice the storage for the
number
float float is used to define floating point numbers
int int is used to define integer numbers
const The const keyword is used to create a read only variable. Once initialized, the value of the
variable cannot be changed but can be used just like any other variable
continue continue allows a new iteration of a loop without the current iteration completing
for The for keyword is used to repeat a block of code many times
do The do keyword performs a similar function to while. Basically, it repeats a block of
statements
while The while keyword is related to do and for. Its purpose is to repeatedly execute a block of
statements
if-else The if-else statement is a two-way decision statement
goto goto allows the program to 'jump' to a named label. The target label MUST be terminated
with a : (colon).
return return will return a value from a function to its caller.
sizeof sizeof will return the number of bytes reserved for a variable or data type.
struct struct is used to declare a new data-type. Basically this means grouping variables together.
typedef typedef is used to define new data type names to make a program more readable to the
programmer.
union The union keyword allows several variables of different type and size to occupy the same
storage location.
void The void keyword allows us to create functions that either do not require any parameters or
do not return a value.
volatile volatile means the storage is likely to change at anytime and be changed but something
outside the control of the user program. This means that if you reference the variable, the
program should always check the physical address, and not use it in a cashed way


1.1.4 C Standard Library Functions

Listed below some ANSI C standard library functions. The header file where related definitions
are stored are given. These may vary on some systems so check local reference manuals. A brief
description is include with all parameter types. More info can be obtained from online man calls or
reference manuals.

Buffer Manipulation
#include <memory.h>
int memcmp (void *s1, void *s2, size_t n) - Compare two buffers.
void *memcpy (void *dest, void *src, size_t n) - Copy one buffer into another .
void *memset (void *s, int c, size_t n) - Set all bytes of a buffer to a given character.

Data Conversion
#include <stdlib.h>
int atoi(char *string) - Convert string to an integer value.
char *itoa(int value, char *string, int radix) - Convert an integer value to a string using given radix.

Directory Manipulation
#include <dir.h>
int mkdir(char *path) - Create a directory u sing given path name.
int rmdir(char *path) - Delete a specified directory.

Input and Output
#include <stdio.h>
FILE *fopen(char *filename, char *access_mode) - Open a file for buffered I/0.
int printf(char *format _string, args) - Write formatted output to stdout.
int scanf(char *format_string, args) - Read formatted input from stdin.

Memory Allocation
#include <malloc.h>
void free(void *mem address) - Free a block of memory.
void *malloc(size_t num bytes) - Allocate a block of memory.

String Manipulation
#include <string.h>
int strcmp(char *string1, char *string2) - Compare string1 and string2 to determine alphabetic order.
char *strcpy(char *string1, char *string2) - Copy string2 to stringl.
int strlen(char *string) - Determine the length of a string.

Time
#include <time.h>
struct_tm *gmtime (time_t *time) - Get Greenwich Mean Time (GMT) in a tm structure.
struct tm *localtime(time_t *time) - Get the local time in a tm structure.
time_t time(time_t *timeptr) - Get current times as seconds elapsed since 0 hours GMT 1/1/70.

1.1.5 Compilation with options
Basic Compilation
The used compiler is the gcc command-line compiler.
Launch a terminal and navigate to your working folder. Create the hello.c source file. Make sure it
is located in this folder by typing ls at the command prompt:
user01% ls
hello.c

You shouldn't see any other files. Compiling hello.c file is done by typing at the command prompt:
user1% gcc -ansi -pedantic -Wall -O2 -o hello hello.c
-ansi: Use ANSI C
-pedantic: Issue all warnings according to strict ANSI standard C
-Wall: Turn on all Warnings. ALWAYS use this. You will benefit from it.
-O2: Optimization Level 2, nearly all supported optimizations that do not involve a space-
speed tradeoff e performed. Increases compilation time, but produces
performance-enhanced code.
-o: Specify output file to be created
Assuming everything went successfully, you should now see two files in your folder:
user01% ls
hello hello.c
Execution
Execution of the program at the command-prompt is done by typing:
user01% ./hello John
The first part following the prompt is the name of the executable (the ./ part indicates in the current
directory/folder). The second and subsequent parts following the prompt form the arguments to the
program. In this case, we are supplying one argument to the hello program - the text John. Executing the
command as detailed above should yield the following:
user01% ./hello John
Hi John!
meaning our executable generated the output uryyb in this case of a the text argument hello. Try other
arguments to ensure the program is behaving as expected.
The gcc -o <name> Option
The -o hello part of the compiler command determined the name of the executable (in our case
hello). We can name the executable whatever we want, so typing:
user01% gcc -std=c99 -Wall -Werror -pedantic -o hello1 hello.c
at the command prompt, followed by ls should produce the following listing:
user01% ls
hello1 hello hello.c
We now have two (equal) executables (hello and hello1) that do the same thing.
The C compilation model presented in Figure 1 is valid for all development environments. For
productivity reasons, instead of command line compiling and building there are used IDEs (Integrated
Development Environments) such that Borland C++, MS Visual C++ 6.0/7.0/7.1, Visual C++ 2005/2008,
etc.

1.1.6 Usage of directives

#define
Use this to define constants or any macro substitution. Use as follows:
#define <macro> <replacement name>
For example:
#define FALSE 0
#define TRUE !FALSE

#undef
This commands undefined a macro. A macro must be undefined before being redefined to a different value.

#include
This directive includes a file into code. It has two possible forms:
#include <file>
or #include ``file''
<file> tells the compiler to look where system include files are held. Usually UNIX systems store files in
\usr\include\directory.

2. Examples

Example 1.Edit sample program area.c

/* Example: C program to find area of a circle */
#include <stdio.h>
#define PI 3.14159

main(){
float r, a;

printf("Enter the circle's radius (in cm): ");
scanf("%f", &r);
a = PI * r * r;
printf("Its area is %3.2f square cm.\n", a);
return;
}
Compiling the program:
% gcc area.c
Execution of the program:
% ./a.out
Compiling the program in different way:
% gcc area.c -o area

Example 2. Edit sample program sum.c

/* Example: C program to compute the sum of first 1000 numbers */
#include <stdio.h>

#define NMAX 1000
main(){
int no = 0;//counter of numbers
int sum = 0;//the sum

while (no < NMAX){
no++;
sum = sum + no;
}
printf ("The sum of first 1000 numbers is: %d", sum);
}

3. Assignments

I.
1) Define a preprocessor macro swap(t, x, y) that will swap two arguments x and y of a given type t.
2) Define a preprocessor macro multiply(x, y) that will multiply two arguments x and y.
3) Write a C program that reads your first and last names and than converts them to upper-case and
lower-case letters. The results will be printed to standard output console.
4) Write a C program to perform basic math operations on two input whole numbers. The basic
operations are addition, subtraction, multiplication, integer division, real division, and modulus (%).
5) Write a C program to perform math operations on two input whole numbers. The operations are:
a) Compute square root of n1
b) Compute square root of n2
c) Raise n1 to the power of n2
d) Inverse n1
e) Inverse n2
6) Refine Example 2 such that the program will compute the sum of numbers that are read from the
standard input.
7) Assume that the following initial values have been assigned to the indicated variables:
int i = 412;
int j = 100;
double x = 987.654321;
For each pair of statements, determine the exact output of each of the following code fragments. Show
your work for each problem.
//(a)
double a = i / j;
double b = (double) (i / j);
printf("\n a = %d", a);
printf("\n b = %d", b);

//(b)
double c = (int)(x * 10.0 + 0.5) / 10;
printf("\n c = %d", c);

//(d)
i = i / j;
j = i / j;
printf("\n i = %d", i);
printf("\n j = %d", j);
II.
1) Define a preprocessor macro to select the least significant bit from an unsigned char
2) Define a preprocessor macro to select the n
th
(assuming least significant is 0) bit from an unsigned
char.
3) Write a C program that displays your first and last names on two consecutive lines on the computer
screen.
4) Write a C program that reads your first and last names as the arguments to the program.
5) Write a program that writes your first and last name on the monitor ten times.
6) Write a program that will count from 1 to 12 and print the count and its square, for each count.
7) Write a program that will count from 1 to 100 and print only those values between 32 and 39, one to a
line.
8) Write a C program that computes the distance a projectile travels before hitting the ground (i.e. its
range), the time it takes for the projectile to hit the ground, and the maximum height of the projectile in
flight, given the angle that it is shot into the air, and its initial velocity (speed) when it is launched. We
will assume that the ground is flat and that the only force present is gravity (no air resistance, etc.).

= angle that the projectile is launched (in whole degrees)
v = initial velocity of the projectile (in meters/second)
g = acceleration due to gravity = 9.8 meters/second2
9) Write a C program that computes the toll for a vehicle traveling on a toll highway. Your main method
will ask the user for the following input data:
- the classification of the vehicle (passenger car, small truck, or large truck) and
- if the vehicle is not a passenger car, the number of miles driven on the toll road
- if the vehicle is a large truck, the weight of the truck in tons.
You may assume that all input numerical data is of the proper form and will not contain negative values or
zero. Depending on the input data value(s), the program will calculate and display the amount of the toll
charge for using the highway.
Toll fees are calculated according to the following rules:
Classification Rate
Passenger Vehicle $2.25
Small Truck $3.00 + $0.40 for each mile
Large Truck $36.00 + $1.10 for each mile beyond 100 miles + $20.00 per ton for the first 5
tons + $25.00 per ton for any additional tons above 5 tons.

The vehicle classification will be entered as two letters ('PC' for Passenger car, 'ST' for Small truck, 'LT' for
Large Truck). All numerical measurements (miles and tons) are entered as integers.
III.

1) Write a C program that takes as argument a file in which first and last name are written on the same
line separated by a space. If the text argument can be opened as a file print the first name and the last
name from the file.
2) Complete the following C code that contains a function that computes how many first class stamps can
be purchased for a given amount of money (in dollars and cents) and how many cents would be left
over after the purchase. Your answers should consist of formulas that will work for any valid value for
numDollars and numCents. You may assume numCents is always between 0 and 99, inclusive.

#include <stdio.h>
int main(void){
// In this example, the user has $20.07 to buy stamps
int numDollars = 20;
int numCents = 7;
int stampCost = 39; // each stamp costs 39 cents

// Compute the maximum number of stamps the user can purchase
int numStamps = __________________________;
// Compute the amount of change (in cents) the user will have left over
int change = __________________________;
printf("\n You can purchase %d stamps.", numStamps);
printf("\n You will have %d cents remaining.", change);
}

For example, the output of this method for the data given should be
You can purchase 51 stamps.
You will have 18 cents remaining.

3) Write a program that begins by displaying you name on the first line as shown below. Then it displays
the upper-case alphabet on the second line as shown below. Then it displays the value 1.23456789 ten
times in succession, twice per line on the next five lines. This must produce the screen output shown
below. Make certain that your numbers line up under the alphabetic characters as shown.
Program Output:
Display your name here
ABCDEFGHIJKLMNOPQRSTUVWXYZ
1.2 1.23
1.23 1.235
1.235 1.2346
1.2346 1.23457
1.23457 1.234568

4) A manufacturer wants you to write a program that will print out a label for a product that has been
manufactured. The label will contain the name of the item, a special serial number, and its month and
year of manufacture.
The serial number is made up of the following in the order shown, separated by dashes:
- A random four digit number that does not start with a 0
- Three random uppercase letters
- A random three digit number that does not contain even digits
- The last character of the item's name in uppercase
Write a C program that asks the user to enter the following information using the keyboard one item at a
time, in the following order:
- the name of the product (which can contain uppercase letters, lowercase letters and blanks, but you may
assume there are no spaces after the last letter, e.g. Brass Floor Lamp)
- the month that the product is manufactured (as an integer between 1 and 12, e.g. enter 1 for January)
- the year that the product is manufactured (as a four-digit integer, e.g. 2007)
The program should then print out a label for the product as shown in the example above.
Sample run:
WELCOME TO THE PRODUCT LABEL MAKER!
Please input the name of the product:
Brass Floor Lamp
Please input the month of manufacture as an integer [1-12]:
1
Please input the year of manufacture as a 4-digit integer (e.g. 2007):
2007
Here is your product label:
*********************************************
BRASS FLOOR LAMP
Serial Number: 4318-VQA-391-P
Manufactured: JAN 07

Das könnte Ihnen auch gefallen