2015-02-09 22 views
0

我无法理解在下面的情形的gcc -pedantic输出:警告:初始值设定元素不是在加载时可计算

$ gcc -pedantic parse.c -lpopt 
parse.c: In function ‘main’: 
parse.c:19:7: warning: initializer element is not computable at load time 
     { "bps", 'b', POPT_ARG_INT, &speed, 0, 
    ^
parse.c:20:7: warning: initializer element is not computable at load time 
     "signaling rate in bits-per-second", "BPS" }, 
    ^
parse.c:27:7: warning: initializer element is not computable at load time 
     { "raw", 'r', 0, &raw, 0, 
    ^
parse.c:28:7: warning: initializer element is not computable at load time 
     "don't perform any character conversions" }, 
    ^

使用以下C代码(从here截取):

$ cat parse.c 
#include <popt.h> 

int main(int argc, const char *argv[]) { 
    char c;   /* used for argument parsing */ 
    int  speed = 0; /* used in argument parsing to set speed */ 
    int  raw = 0;  /* raw mode? */ 
    struct poptOption optionsTable[] = { 
     { "bps", 'b', POPT_ARG_INT, &speed, 0, 
     "signaling rate in bits-per-second", "BPS" }, 
     { "crnl", 'c', 0, 0, 'c', 
     "expand cr characters to cr/lf sequences" }, 
     { "hwflow", 'h', 0, 0, 'h', 
     "use hardware (RTS/CTS) flow control" }, 
     { "noflow", 'n', 0, 0, 'n', 
     "use no flow control" }, 
     { "raw", 'r', 0, &raw, 0, 
     "don't perform any character conversions" }, 
     { "swflow", 's', 0, 0, 's', 
     "use software (XON/XOF) flow control" } , 
     POPT_AUTOHELP 
     { NULL, 0, 0, NULL, 0 } 
    }; 
} 

与代码-ansi-std=c89编译的代码非常相似。为什么-pedantic选项失败?

使用:

$ gcc --version 
gcc (Debian 4.9.1-19) 4.9.1 
Copyright (C) 2014 Free Software Foundation, Inc. 
This is free software; see the source for copying conditions. There is NO 
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 

$ apt-cache policy libpopt-dev 
libpopt-dev: 
    Installed: 1.16-10 
    Candidate: 1.16-10 
    Version table: 
*** 1.16-10 0 
     500 http://ftp.fr.debian.org/debian/ jessie/main amd64 Packages 
     100 /var/lib/dpkg/status 

回答

1

C89标准,初始化列表必须是编译时间常数表达式,因此警告。但在C99中受支持。

C89,你可以这样做:

struct poptOption optionsTable[2]; 

optionsTable[0] = {"bps", 'b', POPT_ARG_INT, &speed, 0, 
    "signaling rate in bits-per-second", "BPS" }; 
optionsTable[1] = {"crnl", 'c', 0, 0, 'c', 
    "expand cr characters to cr/lf sequences" }; 
1

由于可变速度在栈上分配的,其地址在编译时不知道。只有main()执行一次后,它的地址才会被知道。原始变量也一样。就像任何一个好的编译器一样,编译器的错误信息并没有完全指向错误的元素,并且让你头痛,不知道它在抱怨什么。

相关问题