tags:

views:

130

answers:

4
+1  Q: 

issue with FILE

I'm getting the folowing error for below code, "1506-221 (S) Initializer must be a valid constant expression"

FILE          *fp[] = {stdout, dump_f};

is this acceptable? what is the proper way to achive this?

+5  A: 

The error suggests that on your system the stdout variable is in fact a #defined macro which expands to a function call.

Actually, as others have suggested, it's probably just that stdout is an extern declared variable whose value is not known at compile time and therefore can't be supplied in a static initializer.

Regardless of which, the solution should be the same - I'd try something like:

FILE *fp[2];

void init_fp()
{
    fp[0] = stdout;
    fp[1] = dump_f;
}
Alnitak
How would a macro affect the result?
strager
+2  A: 

If that is a global, then C does not support initializing it with a function call. If stdout is a macro (as suggested initially) for a function call, then you won't be able to use it to initialize a global.

MSN

MSN
+2  A: 

More than likely, stdout and/or dump_f are macros or (more likely the problem) external globals.

If I have this code:

// external.c
int hello = 1234;

// external.h
extern int hello;

// main.c
#include "external.h"

int world = hello; // error!

You would receive an error at the indicated line because the value of hello is not known.

stdout and dump_f are most likely declared as extern globals, like so:

extern FILE *stdout, *stdin, *stderr, *dump_f;
strager
+2  A: 

Classically, most Unix systems used to define stdout as something like (&_iob[1]), which reduced to a valid constant expression; Solaris, for instance, still does.

A few years ago, now, the GNU C Library changed its definition of stdout to something that was not a constant, so old code which used to initialize FILE * variables to any of the standard file pointers ceased to compile. This is sanctioned by the C standard, so there is no virtue in complaining. You simply have to accept that you cannot initialize static file pointers to one of the standard I/O channels and recode to get around the problem. (But it is still a nuisance.)

Jonathan Leffler
Yet another reason to hate the FSF.
Norman Ramsey