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.