In some projects I've done in C, I've liked using the following macros which work similar to Perl's warn and die subroutines:
#include <stdio.h>
#include <stdlib.h>
#define warn(...) \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, " at %s line %d\n", __FILE__, __LINE__)
#define die(...) \
warn(__VA_ARGS__); \
exit(0xFF)
Does anything exist like Perl's carp, croak, cluck, and confess subroutines from Carp? I'd like to have something to report errors from the users perspective.
If not, I know there are backtrace() and backtrace_symbols() functions in glibc that along with the -rdynamic gcc option can supply me with a backtrace of function names and code addresses. But i want something a little better; with access to file, line, and function names in the call stack like Perl's caller subroutine. with that I'd be able to write my own libcarp for use in my c programs.
EDIT: 2009-10-19
I'm thinking of creating something that uses gdb when available on basename(argv[0]), then processes the stack trace to produce the different types of messages I want. It should be able to determine if im not in a debuggable executable, or a system without gdb, in which case, carp and cluck will become warns and craok and confess will become dies.
Ive never used gdb like this before (Ive only run it with my program at the beginning, not while its already running). But I found a few functions in glib (g_on_error_stack_trace and stack_trace) that looks very close to what i want to do: It forks a gdb process with the arguments basename(argv[0]) and the process id, then writes to its stdin (which has been redirected to a pipe) the command "backtrace" followed by a "quit". It then reads from its result and parses it the way it likes. This is almost exactly what i need to do.
It appears that nothing exists quite like the Carp module for use in C programs, so i wrote a small library to do it at github.
The library has the following exports defined for use:
and I've added e-varieties of the previous ones for adding errno strings to the warning since i thought it would be useful:
For example if you are writing a library and want to carp about a problem, just use
And it will display the file and line number of the first function calling into your library.
Perl's Carp module uses a different package, instead of a file, to find the suspected subroutine. It also uses the @ISA array or @CARP_NOT recursively to determine which subroutine is outside of a trusted group of packages. I intend to add something similar to this. If the top of the stacktrace is within the trusted scope, then the carp reverts to a cluck (which shows a full stacktrace of the problem) just as this library will do.