Skip site navigation (1)Skip section navigation (2)
Date:      Sat, 3 May 2008 00:05:36 +0300
From:      Kostik Belousov <kostikbel@gmail.com>
To:        Steve Kargl <sgk@troutmask.apl.washington.edu>
Cc:        freebsd-ports@freebsd.org
Subject:   Re: Using stderr in an initialization?
Message-ID:  <20080502210536.GZ18958@deviant.kiev.zoral.com.ua>
In-Reply-To: <20080502202356.GA67129@troutmask.apl.washington.edu>
References:  <20080502202356.GA67129@troutmask.apl.washington.edu>

next in thread | previous in thread | raw e-mail | index | archive | help

--IhRHiOJhC/7Q+39k
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

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.
>=20
> A reduce testcase is
>=20
> #include <stdio.h>
>=20
> typedef FILE *FILEP;
>=20
> static FILEP outfile =3D {stderr};
>=20
> int
> main(int argc, char *argv[])
> {
> 	FILE *fp;
>=20
> 	if (argc =3D=3D 2) {
> 		fp =3D fopen(*++argv, "w");
> 		outfile =3D fp;
> 	}
>=20
> 	fprintf(outfile, "Ouch!\n");
>=20
> 	return 0;
> }
>=20
> GCC gives
>=20
> 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')
>=20
> Yes, I know in the simple example above that I could
> put 'outfile =3D stderr' above the 'if (argc =3D=3D 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
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
stderr
stdin
stdout
=2E.. are expressions of type ``pointer to FILE'' that point to the FILE
objects associated, respectively, with the standard error, input, and
output streams.
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D

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.

--IhRHiOJhC/7Q+39k
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (FreeBSD)

iEYEARECAAYFAkgbgiAACgkQC3+MBN1Mb4ge4wCg4OssQslEMlq5CQ4cjOkNXcYE
KrQAoMQB7f7YW7BZ5qzmmNn8ckRgdgyB
=bHPF
-----END PGP SIGNATURE-----

--IhRHiOJhC/7Q+39k--



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