错误初始化元素不是常量

时间:2011-10-01 23:59:12

标签: c

我的代码遇到问题,我无法解决....

报告错误的代码段:

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

gcc返回的错误是:

initializer element is not constant

3 个答案:

答案 0 :(得分:8)

尝试在main中执行此操作,例如:

static FILE *debugOut;
static FILE *infoOut;

main(){
    debugOut = stderr;
    infoOut = stdout;


}

答案 1 :(得分:7)

ANSI C标准不要求stderr / stdout必须是常量表达式。

因此,取决于使用的标准C库代码,如此

static FILE *debugOut = stderr;

编译或产生您询问过的错误消息。

例如,GNU C library defines stderr / stdout / stdin为非常量表达式。

您基本上有两种选择来处理这种情况,即使这些代码可移植。

从主

初始化
static FILE *debugOut = NULL;
static FILE *infoOut  = NULL;

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

从构造函数初始化

在许多平台上,您可以将函数声明为构造函数,这意味着在调用main()之前调用它。例如,使用GCC时,您可以像这样实现它:

static FILE *debugOut = NULL;
static FILE *infoOut  = NULL;

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

constructor attribute语法未标准化,但由于GCC非常普及,而其他编译器也在努力实现GCC兼容性,因此实际上非常便于使用。

如果您需要将其移植到其他没有类似声明功能的编译器,您可以使用__GNU_LIBRARY__和/或__GNUC__等宏来保护此代码。

答案 2 :(得分:3)

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 <stdio.h>

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;

  ...
相关问题