Using stderr in an initialization?

Kostik Belousov kostikbel at gmail.com
Fri May 2 21:05:41 UTC 2008


On Fri, May 02, 2008 at 01:23:56PM -0700, Steve Kargl wrote:
> I'm porting a piece of code to FreeBSD, and I've run into
> a problem that I currently don't know how to solve. I scanned
> both the Porter's Handbook and the Developer's Handbook, but
> came up empty.
> 
> A reduce testcase is
> 
> #include <stdio.h>
> 
> typedef FILE *FILEP;
> 
> static FILEP outfile = {stderr};
> 
> int
> main(int argc, char *argv[])
> {
> 	FILE *fp;
> 
> 	if (argc == 2) {
> 		fp = fopen(*++argv, "w");
> 		outfile = fp;
> 	}
> 
> 	fprintf(outfile, "Ouch!\n");
> 
> 	return 0;
> }
> 
> GCC gives
> 
> troutmask:sgk[204] cc -o z a.c
> a.c:5: error: initializer element is not constant
> a.c:5: error: (near initialization for 'outfile')
> 
> Yes, I know in the simple example above that I could
> put 'outfile = stderr' above the 'if (argc == 2)'
> statement.  In the much more complicated code, it isn't
> clear where such a change be made.  So, anyone have a
> suggestion on how to change line 5 to satisfy gcc?

The ISO 9899 says that
===========
stderr
stdin
stdout
... are expressions of type ``pointer to FILE'' that point to the FILE
objects associated, respectively, with the standard error, input, and
output streams.
===========

The standards, both for the C language and SUSv3, explicitely allow for
the stderr stream designator to be an runtime-evaluated expression. This
means, it seems, that the code you included makes wrong assumption.

Speaking about the gcc-specific extensions, and still using the C
compiler, I think you may use the __attribute__((constructor)) for
some static function that would assign the stderr value to the static
variable.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 195 bytes
Desc: not available
Url : http://lists.freebsd.org/pipermail/freebsd-ports/attachments/20080502/5a4ed982/attachment.pgp


More information about the freebsd-ports mailing list