Sunteți pe pagina 1din 7

C Laboratory 1 The C Programming Tools

Aims:
• Familarisation with this subject laboratory format.
• Familiarisation with the C programming tools:
o The programming environment (Quincy IDE)
o Editing source code
o Compiling and fixing C syntax errors
o Building and testing programs
o Fixing logical program errors
• Learning to edit, build and run a first C program.
• Practicing modifying a program and re-building.
• Completion of the first laboratory practice sheet this semester.

To Do:
Note: There is rarely enough time to complete the weekly lab work within the two hours
dedicated to the lab instruction. Students are advised to prepare the labs in their own time in
Swinburne open labs prior to the lab session, to complete the lab work as far as it is possible
to do it without help, and to go to the laboratory sessions with questions ready to ask the
instructor in order to complete the lab work.

1 - Expand the self-extracting executable startup file into the directory:


C:\Temp\HIT2080\Lab1\ (ask how to create a directory if you don't know)

This directory contains:


• The C program file for the "Distance" program of Lecture 1, called "distance.c".
• A Practice Sheet where you will record your work in this session.

2 - Open the Practice Sheet


The practice sheet: Lab1PracSheet.rtf is in a format compatible with many word
processors.
Open it now in a word processor, for example Word, and examine it.

Complete the practice sheet as you proceed through the questions rather than doing it at the
end of your practice work. This will save you time!

Page 1 of 7
Note:
Answering questions on the practice sheet will enable you to clarify your knowledge.
A few questions will require some research in order to be answered. Please use the notes, the
text-book, and the web links on "Blackboard" to find out the answers. If still unsure, ask your
fellow students and if still not satisfied, ask the laboratory tutor.

- Fill in question 1 now!

3 - Open Quincy
(Quincy is a simple IDE -Integrated Development Environment- for C or C++ programs.)
To open, from the start menu, select Programs/Quincy 2005/Quincy 2005 (or
something similar).
Open the "distance.c" file.
(File -> Open)
- Go to the project directory: C:\temp\hit2080\lab1
- Select and load distance.c
The "distance.c" file gets loaded into the editor window.

4- Examine the file contents:


- stdio.h is a system header file, where input/output functions (C commands) like printf(),
used in the code are declared.
- math.h is a system header file, where mathematical functions like sqrt(), used in the code
are declared.
- main() is a C function where we write the code to be executed by our program.
The text in the Quincy editor should appear in 4 colours: black, blue, green and red*.

- Fill in questions 2 and 3 now!

The source code of our program is ready to be compiled.

*
If one of these colours is missing,, in Quincy, open the Tools menu, select Options, Click on the Editor Tab, and
click on the last colour box (probably black) and change it to red.

Page 2 of 7
5- Using the Development Tools:
Compiling
As you develop program files one by one, you will need to compile each file and correct any C
language syntax errors. Let's practice doing this:
Select the "Compile" menu entry. [Project]->Compile (or the [f5] key).
This menu entry allows compilation of individual files. It starts the compilation of the file
being currently edited. The IDE loads the C compiler program, called GCC.exe, and starts
translating the human-readable code of the C file into machine code (CPU instructions).
The output window appears and displays the output of the compiler. If no errors were detected,
the output would look like this:

What you will get looks like this:


Several errors are displayed:

Let's tackle the first one:


- Double-click on the error line (showing distance.c:17: the cursor jumps to the corresponding
line in the source code.
The error message says "syntax error before "double". That means that on the previous lime
something was read into the compiler that it didn't expect: the comma.
What about the error on line 26? There is no error on line 26, but the compiler
mistakenly flags it as wrong because of the first error.
You should always fix the errors in the order they appear. Often fixing the first one
will get rid of all the others.
Fix the error and recompile...

Success this time! The compiler has translated our code into machine code and has written
the result into an object file.

- Open Windows Explorer in the Lab1 directory and check that an object file: "distance.o" has
been created there. If you can’t see it, press F5 to refresh the screen.
You can look in the object file by opening it with a text editor: Using Explorer, re-name the file
distance.o to distance.txt
Double-click on it.

You will see some odd characters and some recognisable words (the "string" used by
printf). Note that the comments have been removed (they are ignored by the compiler).

Page 3 of 7
All of the C programming statements have been compiled into machine code, which can be
understood by the CPU (but are cannot be displayed properly by an editor).
Re-name your distance.txt file to distance.o
- Fill in practice sheet questions 4 and 5 now!

Linking
When a program has been compiled, all that remains to be done to obtain an executable, i.e. a
program that can be run by clicking on it with Explorer, is to link it.

Click on Project -> Link (or the Ctrl-F5 key)

The linker (the program that integrates our code with the C function libraries to make the
executable) expects to find a file called distance.o (created before by the compiler from
distance.c). It detects what other files are needed to make an executable (.exe) file and adds
their content to a new executable, "distance.exe".
The linker can find some errors missed by the compiler. On line 27 sqrt (square root) was
misspelt to srt, the program can still compile, but the linker will detect the error and give us
this message:

Note that this time, there are no helpful line numbers. The error was detected while linking the
object file – which has no line numbers. The words: undefined reference to gives
you the clue to the source of the problem. Also the mysterious "ld" is the name of the linker
executable.
The linker thinks that srt is a function name, but it can't find that name in any of the libraries
it's linking to. It is a spelling mistake. We wanted to call "sqrt", the "square root" function, in
order to compute the distance.

Edit the source code to fix the error, then re-compile, and re-link.
Note that you can compile and link at one go by using the "build" menu entry or the hammer
icon ( ).

It works!
If you look into the Lab1 directory you will find that the "distance.exe" executable file has
appeared there.

- Fill in practice sheet question 6 now!

Page 4 of 7
Question: But why did not we get an error message by the compiler earlier? - rather
than the linker? The compiler can give us the error line, while the linker does not
give us that useful information...

Answer:
It is because we are compiling with a low warning level. You can adjust that level
by going to "Tools->Options->Build", and set the warning level to "All" warnings.
Now, restore the error ("srt") and recompile... You'll get a useful warning about the
error on line 27, plus a lot of other warning messages you don't really need. .

- Fill in practice sheet question 7 now!

Testing

We are calculating the distance between two points at locations (1, 5) and (4, 9). The two sides
of the right-angle triangle are therefore 4-1 = 3 and 9-5 = 4. The distance is therefore the
square root of 32 + 42 = 9+16 = 25:
so Distance = 5.00
Execute the program (Click on Project -> Execute or the F9 key or the running man
icon )

If there are no logical errors, the program will display an answer of 5.00, but it's
always possible I made a mistake when typing in the equations...

We see...

Oops! The program displays a distance of 14.32. This cannot be right!

check the code.... here.


Is this correct?
side_2 = y2 + y1;

Unfortunately once our program compiles and links correctly it may still contain errors. The
compiler can only pick errors connected with the C language. If the logic of the program itself
is wrong, then this will be picked by testing.

In this case there is a calculation (logical) error.


Correct the mistake and re-build.

Note that if you click on "execute", or press F9 instead of "build", Quincy is clever
enough to see that distance.c needs re-building and will prompt you to do this.

- Fill in practice sheet questions 8 and 9 now!

Page 5 of 7
6-Run-time errors
Sometimes your program can compile correctly, link correctly and run with no logical errors,
but it may still break down or return the wrong answer in some circumstances. A prime
example is the "blue screen of death" seen on old PCs running Windows 95. On more modern
operating systems, the blue screen has been replaced by a pop-up window like this:

Run time errors can happen if the computer runs out of memory, or mis-uses the memory it
has, or uses a part of memory that is not set up for use (declared) by your program. These
errors happen a lot in C because the C compiler does not check up on or manage memory use
for you.
Here's an example of the mis-use of memory causing the wrong answer to be displayed.
Try changing the 5.2f in the printf statement to 5.2i. Even though the answer is still
calculated as 5, when we print it with the printf statement, the value displayed is probably not
5. This occurs because the wrong formatting string ("%5.2i") was used – the program looked in
the wrong parts of memory to get the value of distance (more on this later). Don't forget the
change the i back to f. %f works with double

Run time errors may also occur if your code tries to perform some impossible mathematical
operation, such as dividing by zero, or taking the square root of a negative number. Try
replacing the '+' in the distance calculation to a '-' like this:
distance = sqrt(side_1 * side_1 - side_2 * side_2);
The output of the compiler detects no errors, but when we run the program we see:

After you've changed it back, try adding this code to your program, after the printf statement,
but before the return statement.
%i works with int
int j = 0;
printf("%i", 1 / j);

The divide by zero error crashes the program. Click on , remove the offending code
and check that the program works correctly.
- Fill in practice sheet question 10 now!

7-Implementing Changes to the Program

Page 6 of 7
Running our Programs
We have so far run our programs (or "executed" them, in other terms) from within Quincy by
clicking "Execute", or pressing F9. Since they are normal programs, we can also execute them
by double-clicking on them from Windows Explorer.

Try it: Double-click with the mouse on "distance.exe"...


The result is far from convincing. We see a black window flicker briefly onto the screen,
then disappear.

Here is why:
Our program is a console program (running on a black Windows screen) .
When we run "distance.exe" from within Quincy, Quincy stops the screen from disappearing
until we press [Enter], but when we execute our programs independently, the window
disappears as soon as the program finishes.

Let's fix this:


We are going to modify our program so that it waits for a key-press before it finishes. That way
the window will remain visible long enough for us to see the result of our program.

In the program, just before the lines:


/* Exit program */
return 0;
add the following two lines:
/* Pause and wait for [enter] */
printf("Press Enter to exit..");
getchar( );

The 1st line is a comment. The 2nd line shows the "Press..." message on the screen. The 3rd
line instructs "distance.exe" to wait for the [Enter] key to be pressed before finishing.

Build the modified program, then run it from Explorer again.

Success at last! The program works and it remains on the screen until we press the [Enter]
key.
- Fill in practice sheet question 11 now!

7- Storing your Program and Practice Sheet


Make sure you have answered all questions on your practice sheet as you finish the lab.

Create a folder (directory) on your flash drive called "HIT2080" and copy your source code
into a subdirectory Lab1 of the folder. You do not need to store the object files or the
executable, since these can be re-built anytime with Quincy. Place the practice sheet document
containing your answers into this directory.
This flash drive (memory stick) will allow you to carry your work between home and the
Swinburne labs. It'll keep a record of your semester lab work for later reference.

As always, keep a backup of all your work!

Page 7 of 7

S-ar putea să vă placă și