Beruflich Dokumente
Kultur Dokumente
Linkage:
Plab Tirgul 3
prog1
Makefiles,
Libraries,
Debugging and
Common Bugs
.o
.o
.o
read.o
main.o
list.o
Compilation:
g++ -c read.c
main.c list.c
.c
.h
read.c read.h
If only one
file is
modified,
will we have
to recompile
all over
again?
.h
.c
list.h list.c
Makefile
prog1
.o
.o
read.o
main.o
list.o
No.
The Makefile
uses the
dependencies
graph
.c
main.c
.c
.h
read.c read.h
.c
main.c
.h
.c
list.h list.c
If read.h is
modified,
what should
be done?
prog1
prog1
.o
We have to
recreate
only a
subset of
the files!
read.o
.o
main.o
.o
list.o
.o
.o
.o
read.o
main.o
list.o
.h
read.c read.h
.c
main.c
.h
.c
list.h list.c
.c
.h
read.c read.h
.c
main.c
.h
.c
list.h list.c
Makefiles: macros
Example:
OBJECTS = read.o list.o main.o
prog1: ${OBJECTS}
g++ ${OBJECTS} -o prog1
.c.o: $*.c
g++ -c
$@
$<
Libraries
Libraries
Library is a collection of functions, written
and compiled by someone else, that you
may want to use
Examples:
Cs standard libraries
Math library
Graphic libraries
Libraries
2 kinds of libraries:
Static libraries:
linked with your executable at compilation time
standard unix suffix: .a
Shared libraries:
loaded by the executable at run-time
standard unix suffix: .so
Static libraries
Using the static library libdata.a:
g++ -o prog object1.o object2.o ldata
Libraries in makefile
libdata.a: ${LIBOBJECTS}
ar rcu libdata.a ${LIBOBJECTS}
ranlib libdata.a
Debugging 101
1.
2.
3.
4.
Use Debugger
Debugger
Allow to monitor run time behavior
Check where the program crashes
Put breakpoints on specific events
Trace execution of the program
Debugger
Debugger can save a lot of time
Find why the program crash
Understand the context (call tree, value of
variables, etc.)
But
Dont be trapped into using debuggers all
the time
Other tools
Intermediate printouts
self-checking code
asserts
Memory allocation & leaks (Lecture)
Dont Panic
There a sensible explanation to the bug
Always!
Dont rush to blame the compiler/OS
Dont attribute bugs to mysterious forces
bug 1
(1)
(2)
(3)
(4)
struct Student {
int id;
char * name;
};
(5)
Student * stud =
(Student *) malloc( sizeof(Student) );
stud->id = 123456;
stud->name =
(char *) malloc(100*sizeof(char));
Memory leak!!!
if (stud != NULL) {
name is not free
free(stud);
}
(6)
(7)
(8)
bug 2
1) void myFunc() {
2)
int * x = randomNum();
3)
int result = *x; //unexpected !
4)
*x = 17; //accessing unallocated space!
5) }
6)
7) int * randomNum() {
8)
int j= srand( time(0) );
9)
return &j;
10) }
bug 3
1) void myFunc(char * input) {
2)
char * name = NULL;
3)
if (input != NULL ) {
4)
name = (char*)malloc(MAX_SIZE);
5)
strcpy(name,input);
6)
}
7)
8)
free( name );
9) }
Always use:
if (output != NULL ) {
free(output);
}
bug 4
1) void myFunc(char * input) {
2)
char * name;
3)
if (input != NULL ) {
4)
name = (char*)malloc(MAX_SIZE);
5)
strcpy(output,input);
6)
}
7)
8)
if ( name != NULL ) {
9)
free( name );
10)
}
11) }