gpt4 book ai didi

C++:具有相同名称的文件范围常量是否违反了一个定义规则?

转载 作者:行者123 更新时间:2023-11-28 00:04:07 24 4
gpt4 key购买 nike

我在 2 个不同的 .cpp 文件中有 2 个常量, 都命名为 const char const * TEXTURE_FILENAME = "...";

一个在 a.cpp 中,另一个在 b.cpp 中,在文件范围内,两个文件都不包含另一个文件,也不应该看到另一个文件,但是VS2010 生成此链接器错误:

a.obj:错误 LNK2005:“char const * const TEXTURE_FILENAME”(?TEXTURE_FILENAME@@3PBDB) 已在 b.obj 中定义

我在这里做错了什么,如何在不需要重命名常量的情况下修复它?

最佳答案

What am I doing wrong here, and how might I fix it without needing to rename either constant?

您正在定义两个名为 TEXTURE_FILENAME 的对象。这就是问题所在。

解决问题的方法不止一种。最简单的解决方法是在文件范围内使它们静态

static const char * TEXTURE_FILENAME = "...";

更新,回应 OP 的评论

TEXTURE_FILENAME 不是 const 对象。它恰好指向 const 的 C 风格字符串。您可以使用以下方法修改文件中其他位置的 TEXTURE_FILENAME:

TEXTURE_FILENAME = <some other C style string>;

要使 TEXTURE_FILENAME 成为 const,您需要使用:

// Both the pointer and what it points to are const.
const char * const TEXTURE_FILENAME = "...";

关于C++:具有相同名称的文件范围常量是否违反了一个定义规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36731455/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com