c programming tools

57
C Programming Tools “UNIX for Programmers and Users” Third Edition, Prentice-Hall, GRAHAM GLASS, KING ABLES 1

Upload: bijan

Post on 18-Jan-2016

30 views

Category:

Documents


0 download

DESCRIPTION

C Programming Tools. “UNIX for Programmers and Users” Third Edition, Prentice-Hall, GRAHAM GLASS, KING ABLES. • Tools that support the various stages of program development : compilation, debugging, maintaining libraries, - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: C Programming Tools

C Programming Tools

“UNIX for Programmers and Users”Third Edition, Prentice-Hall, GRAHAM GLASS, KING ABLES

1

Page 2: C Programming Tools

C Programming Tools

2

• Tools that support the various stages of program development:

compilation, debugging, maintaining libraries, profiling, and source code control.

Page 3: C Programming Tools

C Programming Tools

3

The C Languages

- K&R C - ANSI C

Page 4: C Programming Tools

C Programming Tools

4

SINGLE-MODULE PROGRAMS

We will analyze a simple C program:

- performs a simple task: reversing a string.

- how to write, compile, link, and execute a program that solves the problem using a single source file.

Page 5: C Programming Tools

C Programming Tools

5

Compiling a C Program

- To create and run the “reverse” program,

1) create a subdirectory called “reverse” inside your home directory.

2) create the file “reversefirst.c” using the vi editor

3) compile the C program using the gcc utility.

- By default, gcc creates an executable file called “a.out” in the current directory.

To run the program, type “./a.out”.

Page 6: C Programming Tools

C Programming Tools

6

A Listing of the Corrected “Reverse” Program

/* REVERSE.C */ #include <stdio.h>

/* Function Prototype */ void reverse();

/******************************************/ main() { char str[100]; /* Buffer to hold reversed string */ reverse(“cat”, str); /* Reverse the string “cat” */ printf(“reverse (\” cat \” ) = %s \n”, str); /* Display */ reverse(“noon”, str); /* Reverse the string “noon” */ printf(“reverse (\” noon \” ) = %s \n”, str); /* Display */ } /*****************************************/

Page 7: C Programming Tools

C Programming Tools

7

void reverse(before, after) char *before; /* A pointer to the source string */ char *after; /* A pointer to the reversed string */ { int i; int j; int len; len = strlen(before); for( j=len -1, i=0; j>=0; j--,j++) /* Reverse loop */ after[i] = before[j]; after[len]=NULL; /* NULL terminate reversed string */ )

Page 8: C Programming Tools

C Programming Tools

8

Running a C Program

$ gcc reverse.c $ ls -l reverse.c a.out -rwxr-xr-x 1 glass 24576 Jan5 16:16 a.out* -rw-r--r-- 1 glass 439 Jan5 16:15 reverse.c

$ ./a.out reverse (“cat”) = tac reverse (“noon”) = noon $ _

Page 9: C Programming Tools

C Programming Tools

9

Overriding the Default Executable Name

- to use the “-o” option with gcc, which allows you to specify the name of the executable file that you wish to create:

$ gcc reverse.c -o reverse $ ls -l reverse -rwx-xr-x 1 glass 24576 Jan 5 16:19 reverse* $ ./reverse reverse(“cat”) = tac reverse(“noon”) = noon $ _

Page 10: C Programming Tools

C Programming Tools

10

MULTIMODULE PROGRAMS

- The trouble with the “reverse” program, the “reverse” function cannot easily be used in other programs.

- to write a function that returns a value of 1 if a string is a palindrome and a value of 0 otherwise.

- A palindrome a string that reads the same forward and backward;

for example, “noon” is a palindrome, but “nono” is not.

- use the “reverse” function to implement our “palindrome” function.

Page 11: C Programming Tools

C Programming Tools

11

Reusable Functions

- A better strategy for sharing “reverse()”,

1) compile it separately, 2) and then link the resultant object module into whichever programs wish to use it.

- this technique allows the function to be used in many different programs.

Functions with this property are termed reusable functions.

Page 12: C Programming Tools

C Programming Tools

12

Preparing a Reusable Function

- To prepare a reusable function,

1) create a source-code module that contains the source code of the function, together with a header file that contains the function’s prototype.

2) compile the source-code module into an object module by using the “-c” option of gcc.

Page 13: C Programming Tools

C Programming Tools

13

Preparing a Reusable Function

- reverse.h /* REVERSE.H */ void reverse(); /* Declare but do not define this function */ - reverse.c /* REVERSE.C */ #include <stdio.h> #include “reverse.h”

/********************************************/ void reverse( before, after ) char *before; /* A pointer to the original string */ char *after; /* A pointer to the reversed string */ { int i; int j; int len;

Page 14: C Programming Tools

C Programming Tools

14

len = strlen(before); for( j=len-1, i=0; j>=0; j--, j++) /* Reverse loop */ after[i] = before[j]; after[len] = NULL; /* NULL terminate reversed string */ } - main1.c /* MAIN1.C */ #include <stdio.h> #include “reverse.h” /* Contains the protype of reverse() */ /***********************************************/ main() { char str[100]; reverse(“cat”, str); /* Invoke external function */ printf(“reverse (\”cat\”) = %s\n”, str); reverse(“noon”,str); /* Invoke external function */ printf(“reverse (\”noon\”) = %s\n”, str); }

Page 15: C Programming Tools

C Programming Tools

15

Separately Compiling and Linking Modules

- To compile each source-code file separately, use the “-c” option for gcc. creates a separate object module for each source-code file, each with a “.o” suffix.

$ gcc -c reverse.c main1.c $ ls -l reverse.o mail1.o -rw-r--r-- 1 glass 311 Jan 5 18:24 main1.o -rw-r--r-- 1 glass 181 Jan 5 18:08 reverse.o $ -

Page 16: C Programming Tools

C Programming Tools

16

Separately Compiling and Linking Modules

- To link them all together into an executable called “main1”, list the names of all of the object modules after the gcc command:

$ gcc reverse.o main1.o -o main1 $ ls -l main1 -rwxr-xr-x 1 glass 24576 Jan 5 18:25 main1* $ ./main1 reverse (“cat”) = tac reverse (“noon”) = noon $ _

Page 17: C Programming Tools

C Programming Tools

17

Reusing the Reverse Function

- Here’s the header and source-code listing of the “palindrome” function:

palindrome.h

/* PALINDROME.H */ int palindrome(); /* Declare but do not define */

palindrome.c /* PALINDROME.C */ #include “palindrome.h” #include “reverse.h” #include <string.h> /***********************************************/ int palindrome(str) char *str; {

Page 18: C Programming Tools

C Programming Tools

18

char reverseStr[100]; reverse( str, reversedStr ); /* Reverse original */ return ( strcmp(str, reversedStr ) == 0 ); /* Compare the two */ }

- the program main2.c that tests “palindrome()”

/* MAIN2.C */ #include <stdio.h> #include “palindrome.h” /*************************************************/ main() { printf(“palindrome (\”cat\”) = %d \n”, palindrome(“cat”) ); printf(“palindrome (\”noon\”) = %d \n”, palindrome(“noon”) ); }

Page 19: C Programming Tools

C Programming Tools

19

- To combine the “reverse”, “palindrome”, and “main2” modules

Compile the object modules and then link them.

$ gcc -c palindrome.c main2.c $ gcc reverse.o palindrome.o main2.o -o main2 -rwxr-xr-x 1 glass 24576 Jan 5 19:09 main2* -rw-r--r-- 1 glass 306 Jan 5 19:00 main2.o -rw-r--r-- 1 glass 189 Jan 5 18:59 palindrome.o -rw-r--r-- 1 glass 181 Jan 5 18:08 reverse.o

$ main2 palindrome (“cat”) = 0 palindrome (“noon”) = 1

$ _

Page 20: C Programming Tools

C Programming Tools

20

The Stand-alone Loader: ld

- When cc is used to link several object modules, it transparently invokes the UNIX stand-alone loader, ld, to do the job.

- The loader is better known as the linker.

ld -n {-Lpath}* {objModule}* {library}* {-lx}* [-o outputFile] ld links together the specified object and library modules to produce an executable file.

-n : if you wish to create a stand-alone executable -o : override the default name of the executable, “a.out”, -lx : searches the standard directories “/lib”, “/usr/lib”, and “/usr/local/lib” for a library with the name “libx.a”. -Lpath : to insert the directory path into this search path.

Page 21: C Programming Tools

C Programming Tools

21

Separately Compiling and Linking Modules

- If you link a C program manually,

$ ld mina1.o reverse.o -lc -o main1 –entry main

$ ./main1 reverse (“cat”) = tac reverse (“noon”) = noon

$ _

Page 22: C Programming Tools

C Programming Tools

Debugging Programswith

gdb: GNU Debugger

22

Page 23: C Programming Tools

C Programming Tools

23

Graphical interface: DDD

Page 24: C Programming Tools

C Programming Tools

24

profiling

•http://www.thegeekstuff.com/2012/08/gprof-tutorial/

determine the parts in program code that are time consuming and need to be re-written.

In very large projects, profiling can save your day by not only determining the parts in your program which are slower in execution than expected but also can help you find many other statistics through which many potential bugs can be spotted and sorted out.

How to use gprof

•Have profiling enabled while compiling the code•Execute the program code to produce the profiling data•Run the gprof tool on the profiling data file (generated in the step above).

Page 25: C Programming Tools

C Programming Tools

25

When you’re done: STRIP - The debugger and profiler, utilities both require that you compile a program using special options,

each of which adds code to the executable file.

remove this extra code after debugging and profiling are done with,

Utility: strip { fileName }+

strip removes all of the symbol table, relocation, debugging, and profiling information from the named file(s).

Page 26: C Programming Tools

C Programming Tools

26

When you’re done: STRIP - an example of how much space you can save by using strip:

$ ls -l main2 ---> look at original file. -rwxr-xr-x 1 gglass 5904 Jan 8 22:18 main2* $ strip main2 ---> strip out spurious information. $ ls -l main2 ---> look at stripped version. -rwxr-xr-x 1 gglass 3373 Jan 8 23:17 main2* $ _

Page 27: C Programming Tools

C Programming Tools

27

11.4 유닉스 파일 의존 시스템 : Make

–기능• keeping track of which portions of the entire program

have been changed, compiling only those parts of the program which have changed since the last compile.

–makefile• 파일의 상호 의존 관계의 목록

–make• make 파일을 참조하여 파일을 최신버전으로 개정

Page 28: C Programming Tools

C Programming Tools

28

Unix File-Dependency System: make

Page 29: C Programming Tools

C Programming Tools

29

11.4 유닉스 파일 의존 시스템 : Make

•make [ -f makefile ]–-f : 파일이름 명시 기본이름 : makefile–복수개의 파일과 목적 파일 컴파일

•makefile–이름에 제한이 없으나 파일 이름 뒤에 .make 표기 권장

Page 30: C Programming Tools

C Programming Tools

30

11.4 유닉스 파일 의존 시스템 : Make

•makefile 작성 및 규칙 targetList : dependencyList

commandList•targetList : 목적 파일 목록 •dependencyList : 의존 파일 목록 •commandList : 명령어 목록

( 예 )main1 : main1.o reverse.o

cc main1.o reverse.o -o main1main1.o : main1.c reverse.h

cc -c main1.creverse.o: reverse.c reverse.h

cc -c reverse.c

Page 31: C Programming Tools

C Programming Tools

31

11.4 유닉스 파일 의존 시스템 : Make

•Make 규칙 순서( 예 )

–규칙을 순서대로 조사하면서 상호 의존 트리를 작성–make 는 leaf 노드에서 root 노드까지 진행하면서 부모 노드의 마지막 수정시간이 자식노드의 수정시간보다 이전이거나 없으면 명령어 목록대로 수행

main1

main1.o reverse.o

main1.c reverse.h reverse.c reverse.h

Page 32: C Programming Tools

C Programming Tools

32

11.4 유닉스 파일 의존 시스템 : make

•make 실행( 예 ) $ make [-f main2.make] makefile 이 아닌 경우

결과 cc -c main2.c cc -c palindrome.c cc main2.o reverse.o palindrome.o –o main2

•Make Rules: make 시스템의 추론기능–컴파일 명령의 제거 가능

• cc –c *.c–소스파일명의 제거 가능

• *.c *.o

Page 33: C Programming Tools

C Programming Tools

33

11.4 유닉스 파일 의존 시스템 : make

•Make Rules: make 시스템의 추론기능–컴파일 명령의 제거 가능

•cc –c *.cmain2: main2.o reverse.o palindrome.o cc main2.o reverse.o palindrome.o -o main2main2.o: main2.c palindrome.hreverse.o: reverse.c reverse.hpalindrome.o: palindrome.c palindrome.h reverse.h

Page 34: C Programming Tools

C Programming Tools

34

11.4 유닉스 파일 의존 시스템 : make

•Make Rules: make 시스템의 추론기능–소스파일명의 제거 가능

•*.c *.omain2: main2.o reverse.o palindrome.o cc main2.o reverse.o palindrome.o -o main2main2.o: palindrome.hreverse.o: reverse.hpalindrome.o: palindrome.h reverse.h

Page 35: C Programming Tools

C Programming Tools

35

Touch Utility

•touch -c {fileName}+–updates the last modification and access times of the named files to the current time.

•By default, if a specified file does not exist it is created with zero size. –To prevent this default, use -c option.

•Use touch to force make to recompile files

Page 36: C Programming Tools

C Programming Tools

36

Archiving Modules

•GNU archive utility: ar•ar key archivename {file}*•Creates archive files (.a)

–Add (r, if file is not there)–Remove (d)–Replace (r)–Append (q) adds to end of archive–Table of contents (t)–Extract and copy archive content to current directory (x)–Verbose (v)

$ ar r string.a reverse.o palindrome.o$ ar t string.a$ ar d string.a reverse.o$ ar q string.a reverse.o$ ar x string.a .

Page 37: C Programming Tools

C Programming Tools

static and dynamic library

•static library - .a

•dynamic library - .so

•http://blueamor.tistory.com/707

37

Page 38: C Programming Tools

C Programming Tools

Subversion

David TurnerDec 24, 2007

38

Page 39: C Programming Tools

C Programming ToolsWhat is Subversion?

•Subversion is a version control system.•A version control system allows users to manage files, directories, and the changes made to them.

•Subversion can manage any sort of file collection (not only source code).

39

Page 40: C Programming Tools

C Programming Tools

Working copy

Working copy

Working copy

Repository

Internet

40

Page 41: C Programming Tools

C Programming ToolsReasons to Use Subversion

•You can work more easily with other developers on software development projects.

•You can undo changes to obtain earlier versions of files.•Subversion is well known and free.•Subversion has been under development since 2000.

41

Page 42: C Programming Tools

C Programming Tools

CVS versus Subversion

•Subversion fixes problems with CVS. (See subversion book for details.)

•Subversion is being adopted as a replacement for CVS.

42

Page 43: C Programming Tools

C Programming Tools

Repository versus Working Copy•Project code is stored in a server in a data store referred to as a “repository.”

•Developers “check out” copies of the project code into their local environments. These copies are referred to as “working copies.”

•After making changes to a working copy, the developer “commits” changes to the repository.

•Other developers get these changes by “updating” their working copies.

43

Page 44: C Programming Tools

C Programming Tools

Differentials

∆∆

currentversion

previousversion

previousto thepreviousversion

44

Page 45: C Programming Tools

C Programming Tools

Atomic commits

•A collection of modifications either goes into the repository completely, or not at all.

•In other words, a commit will either altogether succeed, or it will altogether fail.

45

Page 46: C Programming Tools

C Programming Tools

Properties

•Each file and directory has a set of properties—keys and their values—associated with it.

•You can keep certain files from being written into the repository by setting the svn:ignore property to a string that matches the files you want to omit. Such files are said to be “unversioned.”

46

Page 47: C Programming Tools

C Programming Tools

Binary versus Character Data

•Subversion expresses file differences using a binary differencing algorithm, which works identically on both binary and character-based files.

•Both types of files are stored in compressed format in the repository.

•CVS treats these file types differently.

47

Page 48: C Programming Tools

C Programming Tools

The Fundamental Problem

•User A gets a copy of file X from the data store.•User B gets a copy of file X from the data store.•User A changes X and writes the new X back into the data store.

•User B changes his older version of X and writes this into the data store, over-writing A’s changes.

48

Page 49: C Programming Tools

C Programming Tools

Lock-Modify-Unlock

•The lock-modify-unlock solution to the fundamental problem has several problems:

•Two users may want to modify two separate parts of the file, which means one user must wait.

•After locking a file, the user may forget to unlock it.•Locking does not solve incompatibility problems between separate files. (See subversion book for details.)

49

Page 50: C Programming Tools

C Programming Tools

Copy-Modify-Merge

•Subversion uses a copy-modify-merge approach instead of locking.•User A gets a “working copy” of X.•User B gets a “working copy” of X.•User A changes his working copy of X.•User B changes her working copy of X.•A saves his copy of X into the repository.•B tries to save his copy of X into the repository, but it fails, because her changes were made to a now stale version of X

•B performs an “update,” which results in A’s changes to X to be merged into B’s version of X.

• If A’s changes do not conflict with B’s changes, the update silently completes. If A’s changes conflict with B’s changes, subversion inserts annotation into X describing the conflicts and then reports the problem to B. B then manually resolves the conflict.

•Whether B needed to manually resolve conflicts or not, the next step is for B to commit her changes into the repository, which now succeeds.

50

Page 51: C Programming Tools

C Programming Tools

Copy-Modify-Merge in Practice

•With copy-modify-merge, users do not wait on each other.•In practice, conflicts are rare and are usually straightforward to resolve.

•Copy-modify-merge does not work well with binary files, because changes can not be merged. For this reason, subversion provides a lock-modify-unlock process when needed.

51

Page 52: C Programming Tools

C Programming Tools

Revisions

•Subversion transactions are atomic: they either succeed entirely or fail entirely

•After the repository is initially created, it is an empty folder and has revision number 0.

•After committing to a repository with revision number n, the repository is changed to version n+1.

52

Page 53: C Programming Tools

C Programming Tools

Revisions

This diagram and the following text were taken from the online version of the Subversion book.

When Subversion users talk about “revision 5 of foo.c”, they really mean “foo.c as it appears in revision 5.”

53

Page 54: C Programming Tools

C Programming Tools

Revisions and Working Copies

•Working copies do not always correspond to any single revision of the repository; they may contain files from several different revisions.

54

Page 55: C Programming Tools

C Programming Tools

Revisions and Working Copies•User A checks out repository repo.

repo/system.h 3repo/system.cpp 3

•User A modifies system.h and commits this file.

repo/system.h 4repo/system.cpp 3

•User B commits changes to system.cpp, and A updates.

repo/system.h 5repo/system.cpp 5

55

Page 56: C Programming Tools

C Programming Tools

States of a Working File

•Unchanged, and current•Locally changed, and current•Unchanged, and out-of-date•Locally changed, and out-of-date

56

Page 57: C Programming Tools

C Programming ToolsUpdate and Commit

update commit

Unchanged, and current

does nothing does nothing

Locally changed, and current

does nothing writes changes into repo

Unchanged, and out-of-date

replaces working file with new one

does nothing

Locally changed, and out-of-date

merges changes into working file

operation fails with out-of-date error

57