Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 21 May 2001 17:04:35 -0500
From:      John Joseph Trammell <trammell@trammell.dyndns.org>
To:        freebsd-questions@freebsd.org
Subject:   Re: Question for C preprocessor gurus
Message-ID:  <20010521170435.A1610@mn.rr.com>
In-Reply-To: <11895256.990483991242.JavaMail.imail@zero.excite.com>; from john_wilson100@excite.com on Mon, May 21, 2001 at 03:26:30PM -0700
References:  <11895256.990483991242.JavaMail.imail@zero.excite.com>

next in thread | previous in thread | raw e-mail | index | archive | help
On Mon, May 21, 2001 at 03:26:30PM -0700, John Wilson wrote:
> In this program I'm writing, I need to define a simple list of errors, e.g.
> 
> #define ERR_OK     0
> #define ERR_BAD    1
> #define ERR_AWFUL  2
> 
> and a function to return error descriptions:
> 
> char *f(int error_no)
> {
>   switch (error_no)
>   {
>   case ERR_OK:
>      return "OK";
> 
>   case ERR_BAD:
>      return "Bad";
> 
>   /* .... */
>   }
> }
> 
> 
> There is nothing wrong with this code, except one thing - to add a new
> error, I need to do it in two different places.   I was therefore wondering
> if it was possible to avoid adding the same strings twice through (ab)use of
> the preprocessor.

How about defining the error values/symbols/messages in a text file,
then generating the .c and .h files dynamically?

[ ~/test/errno-001 ] cat errors.txt
0 ERR_OK      okily-dokily!
1 ERR_BAD     abandon ship!
2 ERR_AWFUL   my hovercraft is full of eels! 
[ ~/test/errno-001 ] cat gencode.pl

use strict;
my @lines;

while (<>) { chomp; push @lines, $_ }

# make .h file

open(FOO,">foo.h") or die "Can't open foo.h for writing: $!";
for (@lines)
{
        my ($num,$sym) = (split(' ',$_,3))[0,1];
        print FOO "#define $sym $num\n";
}
close FOO;

# make .c file

open(FOO,">foo.c") or die "Can't open foo.c for writing: $!";

print FOO "char *f(int e) { switch (e) {\n";
for (@lines)
{
        my ($sym,$text) = (split(' ',$_,3))[1,2];
        print FOO "\tcase $sym: return \"$text\";\n";
}
print FOO "}}\n";
close FOO;


[ ~/test/errno-001 ] perl -w gencode.pl errors.txt
[ ~/test/errno-001 ] cat foo.h foo.c
#define ERR_OK 0
#define ERR_BAD 1
#define ERR_AWFUL 2
char *f(int e) { switch (e) {
        case ERR_OK: return "okily-dokily!";
        case ERR_BAD: return "abandon ship!";
        case ERR_AWFUL: return "my hovercraft is full of eels! ";
}}
[ ~/test/errno-001 ] 

-- 
If you don't look at the fnord, it can't get you.

To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-questions" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20010521170435.A1610>