c++ 库中的常量; 不起作用
任何人都知道为什么当我尝试包含具有以下声明的库时这不起作用:
namespace wincabase
{
const char* SOMESTRING = "xx";
}
虽然这完全没问题:
namespace wincabase
{
const int X = 30;
}
当我链接库时,我在第一种情况下收到 gcc 的“多个定义”错误。 谢谢!
anyone knows why this does not work when I try to include a library with the following declarations:
namespace wincabase
{
const char* SOMESTRING = "xx";
}
While this is perfectly fine:
namespace wincabase
{
const int X = 30;
}
I get a "multiple definitions" error with gcc for the first case when I link the lib. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
const char* 表示指向 const char 的指针。 这意味着指针本身不是常量。
因此它是一个普通变量,因此您需要
在头文件和
库的一个编译单元中使用。
或者,如果它是指向 const char 的 const 指针,那么您应该使用:
const char* means pointer to const char. This means the pointer itself is not constant.
Hence it's a normal variable, so you'd need to use
in the header file, and
in one compilation unit of the library.
Alternatively, if it's meant to be a const pointer to a const char, then you should use:
您将指针声明为 const,然后将其指向编译单元中定义的字符串文字,因此如果您在头文件中使用它,则将复制字符串文字。 您需要做的是在头文件中声明指针,并在库的源文件中定义字符串。
标题:
在库中的某些源文件中:
You're declaring the pointer as const, and then pointing it to a string literal defined in the compilation unit, so you'd be duplicating the string literal if you used this in a header file. What you need to do is declare pointer in the header file, and define the string in a source file in the library.
Header:
In some source file in the library:
除了 Tobi 指出的方法之外:
另一种选择是将其声明为 const 字符数组:
这种方法可能为编译器提供额外的优化机会,例如将字符串放入生成的二进制文件的只读部分; 尽管可以想象,编译器可能能够使用第一种方法执行类似的优化。
Besides the approach Tobi pointed out:
another alternative is to declare it as a const character array:
This approach potentially provides the compiler with additional optimization opportunities, such as placing the string in the read-only section of the resulting binary; although it's conceivable the compiler may be able to perform similar optimizations with the first approach.
您需要单独声明和定义它们:
You need to declare and define them seprately: