为什么这个.c文件在同一个翻译单元中有两个具有相同标识符的变量?

问题描述 投票:0回答:1

miniz 压缩库类似于 zlib 压缩算法的实现,位于 here miniz-3.0.2.zip 存档中,作为一对 .h 和 .c 文件:

使用方法

可在 releases 获取版本 页作为一对

miniz.c
/
miniz.h
文件,可以简单地添加到项目中。

但是,如果我尝试编译 miniz.c 我收到错误:

Error   C2086   'const mz_uint s_tdefl_num_probes[11]': redefinition

这是在 Visual Studio 上编译。

如果我们查看 .c 文件内部,它有一个变量:

static const mz_uint s_tdefl_num_probes[11];

然后在文件中我们有:

static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 };

这是作者的错误吗?

c miniz
1个回答
0
投票

这确实取决于您使用的 Visual Studio 版本。以下内容将基于 gcc 和 VS2019 构建。我无法访问早期的编译器

#include <stdio.h>

// Empty first
static const int emptyfirst[4];
static const int emptyfirst[4] = {1, 2, 3, 4};

// Full first
static const int fullfirst[4] = {1, 2, 3, 4};
static const int fullfirst[4];

// A second initialization gives an error
//static const int emptyfirst[4] = {4, 3, 2, 1};

// Third declaration
static const int fullfirst[4];
static const int emptyfirst[4];

int main()
{
    printf("%d empty first\n", emptyfirst[0]);
    printf("%d full first\n", fullfirst[0]);
}

这取决于文件扩展名和编译器选项。在 Visual Studio 上,文件扩展名必须是 .c

Properties => Configuration Properties => C/C++ => Advanced => Compile As
应为默认值。

或者,将其设置为/TC。这会将所有源代码编译为 C。如果您将其设置为 /TP,它将编译为 C++,并且您会收到错误。

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