这个问题与为什么需要静态字符 * 而不是静态字符 * 的常量初始化有关
对上述问题的回答告诉我,static const char*
初始化必须是在编译时可解析的地址。同样的答案指出,指针必须是const
,而不是(必然)指针指向的内容。这反映在下面的代码中。
那么,为什么以下代码依赖于目标架构?(即为什么这段代码会在一些但不是所有的交叉编译器上产生编译器错误?)
// main.c
static const char* const text = "foo";
static const char* tmp = text;
int main( int argc, char* argv[] ) { return 0; }
编译成功:
$ /path/to/tgt1-linux-gnu-gcc --version && /path/to/tgt1-linux-gnu-gcc ./main.c && echo $?
tgt1-linux-gnu-gcc (crosstool-NG 1.23.0.485-ee829 - next) 8.2.0
Copyright (C) 2018 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.
0
编译失败:
$ /path/to/tgt2-linux-gnueabi-gcc --version && /path/to/tgt2-linux-gnueabi-gcc ./main.c
tgt2-linux-gnueabi-gcc (crosstool-NG 1.18.0) 4.7.3 20130102 (prerelease)
Copyright (C) 2012 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.
./main.c:4:1: error: initializer element is not constant