C/C++程序调试、Programming编程设计辅导 讲解数据库SQL|辅导留学生 Statistics统计、回归、迭代

- 首页 >> Matlab编程
P2T : C Programming under Linux
Lab 5: Multi-file Projects
Note: Compiling & Executing Code
The source code you write in C is not immediately understandable by the computer as an executable program.
A process known as compilation, which we’ll cover in more depth later in the course, is needed to convert a text file containing
“C source code” into a binary executable, or “program”, which you can run.
The compiler we will be using is called gcc.
For any C program you write, you should save the resulting file with a name ending in “ .c”. gcc is capable of compiling
many different programming languages, and it uses the filename ending to work out which one it should assume a file contains.
With a suitable file—say mycode.c — you can invoke gcc by typing the following into a terminal:
gcc mycode.c
The result of this will be the creation of a new file—called a.out— which contains the result of compiling the code in mycode.c
.
You could then execute the program with
./a.out
If you wanted to call the resulting executable something other than “a.out”, you can use the –o option to change the output
name:
gcc mycode.c –o myexe
Will result in the executable being called “myexe”.
Be very careful not to omit or mix up the order of arguments here. If you type:
gcc –o mycode.c myexe
Then gcc will happily try to overwrite your source code file with the resulting (empty) executable; this won’t work, and
you’ll end up with an empty file (and no source code). This is one reason why I suggest putting the output specifier
after the list of input files—if you miss it off like
gcc myexe –o
Then gcc will shout at you for not telling it where to save the program, rather than messing everything up
Introduction
The purpose of this laboratory is to help you become familiar with the basics of C programming. In this lab we’ll explore
multifile projects, which are discussed in Lecture 6 of the C component of P2T: C Programming under Linux course. It’s assumed
that you will have completed the introductory Linux Lab and are familiar with editing files, compiling code and working
on the command line.
This C Lab contains three Challenge Questions/Exercises, which are the work which you will be marked on. All Challenge
Questions, in all C Labs, are worth 10 points in their respective lab, unless explicitly noted. In general, you can assume that
you will get at least 1, and up to 3, points for laying out well-presented, well-commented code; the rest of the marks will
depend on the question (although partly-functional answers will get marks for the parts which work).
Note: Making an Archive of your Source code to submit Exercises.
There are many tools available to make an archive file containing your source code [and other files] in a single file.
We recommend that you use one of these to allow you to submit a single file for each C Lab.
Tar
The tar program was originally invented to allow files to be packaged together for archiving on magnetic tape (hence “tar”—
”tape archive”). It is still useful today for packaging multiple files together in one place, but its syntax is a little complicated.
To create a tar archive called “lab2.tar” containing multiple individual files, type (at a terminal):
tar cvf lab2.tar myfile.c myotherfile.c
(assuming the files you want are myfile.c and myotherfile.c and are in the same directory as you—you will need to specify
their path otherwise.) You can have as many files as you want listed for inclusion—remember, the first filename is the name
of the archive you’re making, not a file to be added to it!
You can also tar up a whole directory:
tar cvf lab2.tar mydir
You can get tar to list what’s in a tar file with
tar tvf lab2.tar
And you can extract a tar file again with
tar xvf lab2.tar
Zip
Zip is a popular compressed archive creator, available on most platforms.
You can make a zip archive called “lab2.zip” from individual files with
zip lab2.zip myfile.c myotherfile.c
(with assumptions as above for tar)
If you want to zip an entire directory, you need to specify the –r option (for “recursive”):
zip –r lab2.zip mydir
If you don’t specify –r, zip will make a zipfile containing just the name of the directory, and nothing inside it.
To unzip a zip file,
unzip lab2.zip
To just check the files inside a zipfile (without uncompressing it)
unzip –l lab2.zip
Note: C99 Standard features.
Some functionality in code you write may require use of the C99 standard explicitly. This can be enabled by adding the
-std=c99 flag to your gcc
eg
gcc –std=c99 mycode.c –o mycode
Challenge Questions / Exercises
In this part of the C lab you will have to write three C programs based on what has been learned in the lectures and labs up
to this point. In these questions in this lab and later labs, marks are given for code which compiles and runs (even if it
doesn’t meet the specification), good comments and layout, and also for code which performs the required tasks (for the
more complex tasks in later labs, partially working code may get partial marks in this category).
Exercise 1—Refactoring your own code
In Lab 3, you wrote a simple program to print a PGM format image, and in Lab 4, you modified it to split out the code into
multiple functions.
• Starting with your code from Lab 4, split out the function to print out the PGM file into a separate C source file (called
printpgm.c ).
• Create an appropriate header file to allow your function to be used in other code., with a suitable prototype.
• Modify the code in the original file to include the header file appropriately.
• Compile your two C files,
• and link appropriately,
• and test that the code still does what it is supposed to do.
• Write an appropriate makefile so that anyone can compile the full code,
• and add appropriate compiler flags to enable debugging (-g) and the C99 standard (-std=c99).
• The makefile from Exercise 3 may help with this as a starting point.
You should have appropriate comments in all of the files, including the makefile, and present your code in a consistent and
readable manner.
Three C source code files (2 .c , 1 .h), and one makefile, are your submission for this exercise.
Exercise 2—External Libraries
At one point in time, programming was taught to children at school using a language called “Logo”, which allowed you to
direct a “turtle” around a screen, drawing shapes as it travelled.
We provide you with a C library, libturtle.a , and a header file turtle.h, to allow you too to experience the magic of Logo, via
C... (Both of these are located in /usr/share/p2t/lab05/ )
• By reading the header file, develop an understanding of the use of the libturtle library.
• (Essentially, you have functions which turn drawing on and off, let you set the colour you will draw with, and
let you direct the “turtle” in various directions and distances.)
• Hence, write a single-file program with just a main function in it, which:
• creates a 256 by 256 pixel image,
• and draws a regular polyon with N sides,
• saving it to a file called “mylogo.png”.
(Continued on page 4)
• N should be provided by a command line argument (not an interactive prompt!).
• The code should exit with a helpful line of text if called with no command line argument.
• (Hint: the internal angles of a regular N-gon are 180 × (N−2)/ N degrees. The exterior angles are 360/N degrees.)
• The Mathworld page for Regular Polygon may be of use, depending on how complicated you want to be: http://
mathworld.wolfram.com/RegularPolygon.html - if you need more mathematical functions, you will have to use libm,
of course.)
• Additionally, write code so that if the program is executed with the name “square”, it does the same thing as if it is
called with the command line option 4 (that is, draws a 4 sided regular polygon).
• (Hint: what does argv[0] contain?)
• Compile and appropriately link the program (you will also need to link the math library as well as libturtle).
• Create a simple makefile to automate this, building a copy of the program called “polygon” and a copy called
“square”.
Your submission for this exercise is a single C source code file, and a makefile, submitted together.
30% of the marks for this exercise are for appropriate layout and comments. (3)
(Continued from page 3)
Continued on next PAGE.
Exercise 3—Refactoring someone else's code; libm
This code uses the sqrt (square root) and cbrt (cube root) functions which are declared in the standard library header called
math.h, which is implemented in the library libm.a (or libm.so).
You are also provided with a makefile in /usr/share/p2t/lab05/ .
(Continued on page 6)
//Calculate the real offset of the complex cube roots of a real , given the real root
double re_complexroots(double);
// Calculate the imaginary parts of the complex cube roots of a real , given the real root
double im_complexroots(double);
//try to parse input appropriately
double validate_input(int argc , char * argv[]);
int main(int argc , char * argv[]) {
double x, cub_x , re_cub_x , im_cub_x;
x = validate_input(argc , argv);
cub_x = cbrt(x);
re_cub_x = re_complexroots(cub_x);
im_cub_x = im_complexroots(cub_x);
printf("The cube roots of %f are %f, %f + %fi and %f - % fi.\n", x, cub_x ,
re_cub_x , im_cub_x , re_cub_x , im_cub_x );
return 0;
}
double re_complexroots(double z) { return -1.0*z/2.0 ; }
double im_complexroots(double z) { return sqrt(3.0)*(z/2.0); }
double validate_input(int argc , char * argv[]) {
if (2!=argc) {
fputs("Too many inputs - just enter one double!", stderr );
exit(1);
}
double val;
int parsed = sscanf(argv[1], "%lf", &val );
if (0== parsed) {
fputs("Could not parse input as a double!", stderr);
exit(1);
}
return val;
}
For Interest 1—Optimisation and Compilation Flow in Detail
THIS SECTION IS OPTIONAL AND NOT FOR CREDIT
In /usr/share/p2t/lab05/optional there are some C source files. Read them to see what they do.
• Using the -E option to gcc, see what happens when the file main.c is preprocessed.
• Using the -S option to gcc, see what main.c and function.c look like when compiled to assembly. You don’t have to understand
assembly, but see if you can spot any of the values assigned in the C code.
• Using the -S option and the -On option, with n from 1 to 3, to turn on optimisation, check that the generated assembly
changes when you compile the C source, for example, using the diff command.
• (Can you see how it has optimised main.c ?)
• Can you see what the difference between -O2 and -O3 is when compiling function.c?
• Using the -c option to gcc, make two object code files from the two C source files.
• The program objdump can process an object file and tell you various things about its contents.
• Using: objdump –d function.o
• Verify that the contents of the object file's code looks like that in the assembly file (function.s)
• Using the -o option to pick an executable name, link the two object files into one executable, and then execute it.
• (Does the result match what you expected? IF not, why not?)
• Based on the expectations in the makefile:
• split the code up into 3 .c source files, and an appropriate number of header files, adding lines where necessary
• (also add 9 appropriate comments).
• You will need to add one piece of additional information to the makefile as well.
• Hence compile the project using the modified makefile.
• Add a README file to the project explaining how to build it.
You should use appropriate comments in all files, and present your code in a consistent and readable manner.
Your submission for this lab is 3 C source files (.c), the correct number of C source header files (.h), a README text file, and a
makefile, all together.
(Continued from page 5)

站长地图