Gowtham wrote:
> Hi,
>
> I had some C code written which initialized a global variable as:
>
> FILE *yyerfp = stdout;
In C, stdin, stdout and stderr are macros. They needn't be
constant expressions.
> This used to work fine in older versions of gcc. Now, when I
> tried to compile this code (with gcc 3.2.3),
> I got errors like:
>
> ../Include/Message.h:42: initializer element is not constant
That is your error, not glibc's.
> I looked around the www and found that stdin/stdout/stderr
> are *not* made const in the newer versions of gcc.
They don't need to be.
> As a work-around, I thought of this:
>
> FILE *yyerfp; // Uninitialized global
Actually, it's zero initialised (to a null pointer).
> // Initialize it in a separate function
> void initializeGlobals( void )
> {
> yyerfp = stdout;
> }
>
> int main( ... )
> {
> // Initialize the global before doing anything else
> initializeGlobals();
> ...
> // Do other things
> }
>
> But, this code will also be compiled into a shared object,
> dynamically loadable from other languages such as perl etc.
> and I do not want to change the API interface there.
Fine, but in a sense, it's your interface that is a problem.
> If I follow this approach, I also have to add the
> initializeGlobals() call in every perl program which uses
> this library.
Replace it with a macro/function like...
#define YYERFP \
(yyerfp ? yyerfp : (yyerfp = stdout))
int library_foo()
{
FILE *fp = YYERFP;
...
}
<OT> The other choice of course is C++ </OT>
> What is the best way of solving this problem?
Don't make libraries dependant on non-zero initialisation of
static variables.
--
Peter


|