|
|
Debugging C Code with line number output at runtime
Assume you call a C function and it returns -14. Nice, eh ? Would be cool to
see an actual error message instead of -14 to debug it more efficiently. This is actually very easy.
Look at the source code below:
debug.c
// compile with:
// # gcc -o debug debug.c
#include <stdlib.h>
#include <stdio.h>
#define CHECK(arg) check(arg, __LINE__)
int check(int r, int n) {
if (r != 0) {
fprintf(stderr, "Error \"%s\" in line number %d\n", strerror(-r), n);
// exit; // exit here if the error is critical
}
return(r);
}
int function(void) {
// just return a negative number
// usually you check a function which returns -EINVAL, -ENODEV etc.
return -2;
}
int main(int argc, char *argv[]) {
int test;
test = CHECK( function() );
return 0;
}
As you see there are 2 possibilities: Either the error or return value is
non-critical, then it's save to proceed with the program.
But if the error is critical, just exit in the check function. Make sure
you do some cleanup of other stuff before exiting.
The definition of the error codes, e.g. ENODEV, EINVAL are in the linux kernel include files:
include/asm-generic/errno-base.h
include/asm-generic/errno.h
Last-Modified: Sat, 04 Feb 2006 16:03:16 GMT
|
|