Error initializer element is not constant

前端 未结 3 628
感动是毒
感动是毒 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条回答
  •  滥情空心
    2021-01-11 23:30

    The ANSI C standard does not demand that stderr/stdout have to be constant expressions.

    Thus, depending on the used standard C library code like this

    static FILE *debugOut = stderr;
    

    compiles or yields the error message you have asked about.

    For example, the GNU C library defines stderr/stdout/stdin as non-constant expressions.

    You have basically two options to deal with this situation, i.e. to make such code portable.

    Initialization from main

    static FILE *debugOut = NULL;
    static FILE *infoOut  = NULL;
    
    int main(int argc, char **argv)
    {
      debugOut = stderr;
      infoOut  = stdout;
      // [..] 
      return 0;
    }
    

    Initialization from a constructor function

    On many platforms you can declare a function as constructor, meaning that it is called on startup before main() is called. For example when using GCC you can implement it like this:

    static FILE *debugOut = NULL;
    static FILE *infoOut  = NULL;
    
    static void init_streams(void) __attribute__((constructor)); 
    static void init_streams(void)
    {
      debugOut = stderr;
      infoOut  = stdout;
    }
    

    This constructor attribute syntax is not standardized, but since GCC is very widespread and other compilers strive for GCC compatibility this is actually quite portable.

    In case you need to make this portable to other compilers that does not have a similar declaration feature you can guard this code with macros like __GNU_LIBRARY__ and/or __GNUC__.

提交回复
热议问题