0

考虑这段代码:

enum 
{
        ERR_START,
        ERR_CANNOTOPENFILE, 
        ERR_CANNOTCONNECT, 
        ERR_CANNOTCONNECTWITH,
        ERR_CANNOTGETHOSTNAME,
        ERR_CANNOTSEND,

};

char* ERR_MESSAGE[] =
{
    [ERR_START]                     = "Nothing",
    [ERR_CANNOTOPENFILE]            = "Cannot open '%s' filename.\n",
    [ERR_CANNOTCONNECT]             = "Cannot connect.\n",
    [ERR_CANNOTCONNECTWITH]         = "Cannot connect with '%s'.\n",
    [ERR_CANNOTGETHOSTNAME]         = "Cannot get host name.\n",
    [ERR_CANNOTSEND]                = "Cannot send.\n",

};

鉴于此错误:

error.h:27:1: error: parameter ‘ERR_MESSAGE’ is initialized
error.h:29:2: error: array index in non-array initializer
error.h:29:2: error: (near initialization for ‘ERR_MESSAGE’)
error.h:29:2: warning: initialization from incompatible pointer type
error.h:30:2: error: array index in non-array initializer
[....]

我正在用-std=c99.

如何解决这个问题?

4

1 回答 1

3

我认为您收到此消息是因为文件中存在另一个语法错误(或之前包含的内容)。我将代码粘贴到一个独立的 C 文件中,并且没有编译错误,gcc -std=c99 -c test.c我的 GCC 版本是gcc (GCC) 4.6.3 20120306 (Red Hat 4.6.3-2)

一个可能的错误(可能是唯一的错误)是函数声明缺少分号。用代码

enum 
{
        ERR_START,
        ERR_CANNOTOPENFILE, 
        ERR_CANNOTCONNECT, 
        ERR_CANNOTCONNECTWITH,
        ERR_CANNOTGETHOSTNAME,
        ERR_CANNOTSEND,

};

void foo()
char* ERR_MESSAGE[] =
{
    [ERR_START]                     = "Nothing",
    [ERR_CANNOTOPENFILE]            = "Cannot open '%s' filename.\n",
    [ERR_CANNOTCONNECT]             = "Cannot connect.\n",
    [ERR_CANNOTCONNECTWITH]         = "Cannot connect with '%s'.\n",
    [ERR_CANNOTGETHOSTNAME]         = "Cannot get host name.\n",
    [ERR_CANNOTSEND]                = "Cannot send.\n",

};

我收到类似的错误

est.c: In function ‘foo’:
test.c:13:1: error: parameter ‘ERR_MESSAGE’ is initialized
test.c:15:5: error: array index in non-array initializer
test.c:15:5: error: (near initialization for ‘ERR_MESSAGE’)
test.c:15:5: warning: initialization from incompatible pointer type [enabled by default]
test.c:15:5: warning: (near initialization for ‘ERR_MESSAGE’) [enabled by default]
test.c:16:5: error: array index in non-array initializer
test.c:16:5: error: (near initialization for ‘ERR_MESSAGE’)
test.c:16:5: warning: excess elements in scalar initializer [enabled by default]
test.c:16:5: warning: (near initialization for ‘ERR_MESSAGE’) [enabled by default]
[...]
于 2012-06-29T20:31:32.803 回答