c++:变量的多个定义,但没有在其他地方定义
C++: Multiple definition of variable, but not defined somewhere else?
我目前正在尝试编译我的一些旧代码,这些代码从未产生任何问题-直到现在我在Ubuntu中再次使用它。(gcc 4.8.2)
这个问题是由#define中的随机数生成器引起的,文件看起来基本上是这样的:
**Lights.h:**
#if defined(__linux) || defined(__linux__)
unsigned int seed = time(NULL);
#define RND ((double)rand_r(&seed)/RAND_MAX) // reentrant uniform rnd
#endif
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
#define RND ((double)rand()/RAND_MAX) // uniform rnd
#endif
class Lights {
.... //various structs and functions, using RND
}
**Lights.cpp**
#include Lights.h
....
//implementation of functions, also using RND
这个工作总是没有问题,但现在我在编译时得到以下错误:
CMakeFiles/luxrender.dir/qtgui/lightSourceCleaner.o: In function `qt_noop()':
/home/.../Lights.cpp:131: multiple definition of `seed'
CMakeFiles/.../mainwindow.o:/home/.../mainwindow.cpp:103: first defined here
CMakeFiles/...mainwindow.o: In function `MainWindow::startLsc()':
mainwindow.cpp:(.text+0x167b4): undefined reference to `Lights::cleanLightGroups(QProgressDialog&, int, int, int, double, double, double, bool, bool, double, double)'
collect2: error: ld returned 1 exit status
make[2]: *** [luxrender] Error 1
make[1]: *** [CMakeFiles/luxrender.dir/all] Error 2
所以我在这里有点困惑,因为mainwindow.cpp中没有重新定义"seed",事实上,第103行涉及到一个我从未在此上下文中使用的函数(它与日志记录有关)
我不知道qt_noop()是什么(可能与QT GUI相关,但在这种情况下我也从未接触过这个)。
"seed"在其他地方没有定义,只有Lights.h有这个#define,而Lights.h只包含在mainwindow.cpp中。
你知道是什么问题吗?(正如我说的,这是有效的,但这是2年前的事了——gcc 4.8.2最终有什么改变吗?)
它是在头文件中定义的,这意味着在每个包含头文件的翻译单元中都会有一个定义;因此有多个定义,因为您从多个地方包含它:Lights.cpp
和mainwindow.cpp
。相反,只需在头文件中声明:
extern unsigned int seed;
并在一个源文件中定义它:
unsigned int seed = time(NULL);
然后再考虑是否需要一个全局变量,以及是否要使用不可靠的rand
函数和不可靠的种子。
相关文章:
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 这个失败的测试是将零添加到空指针未定义的行为、编译器错误还是其他什么?
- 如何创建没有特定定义的随机分布?uniform_int_distribution是从其他类继承的吗?
- error dllimport 函数的定义不允许在一个特定的联合中,而其他类、结构和联合将按预期导出
- 在命名空间中声明变量,在 main 中定义它,使其对所有其他文件可见
- 如何定义此"if block"中其他无效输入的值,以便在c ++中将字符串转换为对象?
- C++ 在多个其他类中使用单个类 - 编译时出现多个定义错误
- 错误 LNK1104:错误消息中显示的路径未在其他依赖项中定义
- GlM(OpenGl Mathematics)库阻止M_PI和其他定义的常量工作
- 如何使 extern 方法在共享库中定义,但使用 cmake 在其他目标中声明?
- 如何使用使用代替定义或其他C++功能
- 使用类的其他成员变量定义类的成员变量数组
- C++ 在构造函数中传递数组而不在其他地方定义它们
- 如何在不定义其他 fonction getValue() 的情况下获取私有值
- 在编译时获取枚举类大小,而无需定义其他元素
- 定义其他名称空间的少量用法可以吗
- c++如何定义其他开发人员需要调用的常量函数顺序
- 为什么我们能够在类定义中定义[static const int],而不能定义其他静态const类型
- bcc32 + nasm obj 链接错误(致命:"fir.asm":需要在 .def 文件中定义其他段)
- 定义其他类中的对象