如何避免在 C++ 中意外地重新声明全局常量?
我在名为“Matrix.h”的标头中定义了一个模板矩阵类。
我的程序中重复使用某些矩阵。 我想我应该在“Matrix.h”头文件中定义这些,如下所示:
const Matrix<GLfloat> B_SPLINE_TO_BEZIER_MATRIX(4, 4, values);
当我这样做时,g++ 抱怨我重新定义了有问题的常量。 发生这种情况是因为我将 Matrix.h 包含在两个不同的源文件中。 当编译这些目标文件时,两者最终都会得到上面矩阵的定义,从而导致错误消息。
我的问题是如何避免这种情况? 我想要一个可供多个文件访问的常量,但我不知道将其放在哪里。
I have a template matrix class class defined in a header called "Matrix.h".
Certain matrices are used repeatedly in my program. I thought that I would define these in the "Matrix.h" header file, like so:
const Matrix<GLfloat> B_SPLINE_TO_BEZIER_MATRIX(4, 4, values);
When I do this g++ complains that I redefined the constant in question. This happens because I include Matrix.h in two different source files. When the object files for these are compiled, both end up with a definition of the matrix above, causing the error message.
My question is how do I avoid this situation? I want a constant that is accessible to more than one file, but I don't know where to put it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以通过以下方式避免它:
extern
。 一个符号可以被声明任意多次。You avoid it by:
extern
in the header. A symbol can be declared any number of times.如果您不想将其拆分为头文件和实现文件,
声明常量
static
(或在匿名命名空间中声明它)以使定义私有。 链接器不会抱怨,但会导致跨编译单元产生多个私有副本。创建一个返回常量的内联函数。 内联函数定义在目标文件中产生“弱”符号,因此链接器将消除重复项并选择一个。
If you don't want to split it between a header and implementation file,
Declare your constant
static
(or declare it in anonymous namespace) to make definition private. Linker will not complain, but it will result in multiple private copies across compilation units.Make an inline function that returns the constant. Inline function definitions produce "weak" symbols in object file, so linker will eliminate duplicates and pick one.
只需像这样编写头文件
#ifndef HEADER_FILE_NAME_H
#define HEADER_FILE_NAME_H
// 你的头文件代码
#endif
这将确保它不会被多次声明
just write your header file like this
#ifndef HEADER_FILE_NAME_H
#define HEADER_FILE_NAME_H
// your header file code
#endif
this will make sure that it won't get declared multiple times
将头文件 (.h) 包装在预处理器条件中,以防止它们两次包含在编译器的符号表中:
HEADER_NAME 实际上可以是任何内容,但最好确保它与文件相关,以防止更多冲突,因为这是只需定义一个空的预处理器宏(它也最终出现在符号表中)。
Wrap header files (.h) in preprocessor conditionals to prevent them from being included in the compiler's symbol table twice:
HEADER_NAME can really be anything, but it's best to make sure that it's something related to the file to prevent more collisions, as this is just defining an empty preprocessor macro (which also ends up in the symbol table).