共享标头导致多重定义符号错误
考虑以下头文件示例: shared_example.h
#ifndef SHARED_EX
#define SHARED_EX
const int Shared_Int = 1;
const char * Shared_CString = "This is a string";
#endif
shared_example.h 文件包含在多个编译单元中,这会导致链接器(正确地)抱怨:
错误 LNK2005:“char const * const Shared_CString”(?Shared_CString@@3PBDB) 已在 First_Compilation_Unit.obj 中定义
从中删除 Shared_CString 常量文件消除了该问题。
所以,我有两个问题。
首先,为什么 Shared_Int 常量不会触发同样的问题?
其次,允许单独的编译单元使用相同的常量字符串值的适当方法是什么?
Consider the following header file example: shared_example.h
#ifndef SHARED_EX
#define SHARED_EX
const int Shared_Int = 1;
const char * Shared_CString = "This is a string";
#endif
The shared_example.h file is included in multiple compilation units, which leads the linker to (correctly) complain that:
error LNK2005: "char const * const Shared_CString" (?Shared_CString@@3PBDB) already defined in First_Compilation_Unit.obj
Removing the Shared_CString constant from this file eliminates the issue.
So, I have two questions.
First, why doesn't the Shared_Int constant trigger the same issue?
Second, what is the appropriate way to allow separate compilation units to make use of the same constant string value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第一个声明是一个常量整数值。在 C++ 中,
const
默认情况下具有内部链接。第二个声明是指向 const char 的指针。该声明本身不是 const,并且没有其他链接说明符,因此它没有内部链接。如果将声明更改为 const char * const ,它将成为指向 const char 的 const 指针并具有内部链接。
The first declaration is of a constant integral value. In C++,
const
has internal linkage by default.The second declaration is of a pointer to
const char
. That declaration is notconst
itself, and has no other linkage specifiers, so it does not have internal linkage. If you changed the declaration toconst char * const
it would then become a const pointer toconst char
and have internal linkage.shared_example.h
shared_example.c
shared_example.h
shared_example.c
使它们静态即可解决问题。
您没有看到 Shared_Int,因为您没有在编译的多个 c 模块中使用它。
编辑:我的错 - 我所说的对 C 有效。没有看到 c++ 标签。对不起
Making them static will solve the issue.
You are not seeing the Shared_Int because you are not using it in more then one of the c modules that you compile.
Edit: My bad - what I say is valid for C. Didn't saw the c++ tag. Sorry