我如何引用C中需要它的函数后出现的静态数据?

问题描述 投票:3回答:2
#include <stdio.h>
typedef unsigned char uint8_t;
// I want this at the end of the file
//static const uint8_t hello[] = { 'H','e','l','l','o',' ','W','o','r','l','d','!','\0'};
int main()
{   // how do I declare a forward reference to 'hello' here?
    printf("%s\n", hello);
    return;
}
// but down here, the linker can't resolve it
static const uint8_t hello[] = { 'H','e','l','l','o',' ','W','o','r','l','d','!','\0'};

错误C2065'hello':未声明的标识符

出于装饰性原因,我想将大型静态数据表放在c源文件的末尾。但是我该如何引用呢?我在函数中使用了前向引用来解析稍后出现在文件中的函数,但是静态变量使我头疼。我尝试了extern(作为最后的希望),但是链接器看起来在模块之外(这很有意义),但是仅在需要它的函数之后的几行就无法解析为darn变量。这是C限制(我已经在两个编译器上尝试过此限制),还是我只是缺少一些明显的东西?

c static forward-declaration linkage
2个回答
2
投票

我想将大型静态数据表放在c源文件的末尾。但是我该如何引用呢?

使用临时定义

static const uint8_t hello[13 /* more */];

int main(void) {
  ...
}

static const uint8_t hello[] = { 
    'H','e','l','l','o',' ','W','o','r','l','d','!','\0' };

引用城市。关于static const uint8_t hello[];是否应有合理的分歧。我使用的编译器禁止它与我对规范的阅读相匹配。

6.9.2外部对象定义具有文件范围而没有初始化程序,没有存储类说明符或具有存储类说明符static的对象的标识符声明构成[暂定定义。如果翻译单元包含一个或多个标识符的临时定义,并且翻译单元不包含该标识符的外部定义,则该行为就好像该翻译单元包含该标识符的文件范围声明,且复合类型为最后的转换单元,其初始值设定为0。

如果对象标识符的声明是一个临时定义,并且具有内部链接,则声明的类型不得为不完整的类型。 C17§6.9.2 2&3

J.2未定义行为

使用内部定义(6.9.2)声明具有内部链接和不完整类型的对象的标识符。

2
投票

您在这里。

© www.soinside.com 2019 - 2024. All rights reserved.