Managing error strings in C
Dan Salomon
salomon at ccu.umanitoba.ca
Wed Jan 16 08:20:17 AEST 1991
In article <1991Jan10.122227 at lotus.lotus.com> blambert at lotus.lotus.com (Brian Lambert) writes:
>Hi:
>
>I was wondering if anyone out there had any clever ways of handling
>error messages in C. That is, in small/medimum size programs one
>usually winds up with all sorts of:
>
> PrintLog("Memory allocation error");
>
>lines in the program. I have seen code where people define an array of
>char pointers to error messages used in the program such as:
>
> char *errors[] = {
> "Memory allocation error",
> "Can't open file",
> ...
> };
>
> #define NO_MEMORY 0
> #define CANT_OPEN 1
One method that worked fairly well for me was to write an error
message preprocessor program. The error messages are stored in
an easy to maintain data file, and a program generates .h files
from that data file. I.e:
-------------------
| Error message |
| data file |
| "errors.dat" |
-------------------
|
V
|
-------------------
| Error message |
| preprocessor |
-------------------
/ \
/ \
/ \
------------------- -------------------
| Error code | | Error message |
| definition file | | init file |
| "err_codes.h" | | "err_mess.h" |
------------------- -------------------
The files will look something like the following:
errors.dat
----------
NO_MEMORY "Memory allocation error"
CANT_OPEN "Can't open file"
... ...
err_codes.h
-----------
#define NO_MEMORY 0
#define CANT_OPEN 1
...
err_mess.h
----------
char *errors[] = {
"Memory allocation error",
"Can't open file",
...
};
The preprocessor is trivial to write, since it is just copying strings
from one file to another and maintaining a counter. The data file is
easy to maintain, since it doesn't need to include all the messy C
punctuation. A utility like make can be used to rerun the preprocessor
automatically every time the data file is modified.
--
Dan Salomon -- salomon at ccu.UManitoba.CA
Dept. of Computer Science / University of Manitoba
Winnipeg, Manitoba, Canada R3T 2N2 / (204) 275-6682
More information about the Comp.lang.c
mailing list