Error initializer element is not constant

前端 未结 3 590
感动是毒
感动是毒 2021-01-11 22:49

I am having trouble with my code, and I can not solve ....

the code snippet where the error is reported:

static FILE *debugOut = stderr;
static FILE          


        
3条回答
  •  -上瘾入骨i
    2021-01-11 23:16

    From the C99 standard:

    6.7.8 Initialization

    Constraints

    4 All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

    Hence,

    static FILE *debugOut = stderr;
    static FILE *infoOut = stdout;
    

    is not legal code if compiler does not think stderr and stdout are constant expressions.

    This is what the standard has to say about stderr and stdout.

    7.19 Input/output

    7.19.1 Introduction

    ...

       stderr
       stdin
       stdout
    

    which are expressions of type ‘‘pointer to FILE’’ that point to the FILE objects associated, respectively, with the standard error, input, and output streams.

    Solution

    The standard compliant way to deal with this is to initialize the variables to NULL and set their values in main.

    static FILE *debugOut = NULL;
    static FILE *infoOut  = NULL;
    
    int main()
    {
      debugOut = stderr;
      infoOut  = stdout;
    
      ...
    

提交回复
热议问题