c++:变量的多个定义,但没有在其他地方定义

C++: Multiple definition of variable, but not defined somewhere else?

本文关键字:定义 其他 方定义 变量 c++      更新时间:2023-10-16

我目前正在尝试编译我的一些旧代码,这些代码从未产生任何问题-直到现在我在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.cppmainwindow.cpp。相反,只需在头文件中声明:

extern unsigned int seed;

并在一个源文件中定义它:

unsigned int seed = time(NULL);

然后再考虑是否需要一个全局变量,以及是否要使用不可靠的rand函数和不可靠的种子。

相关文章: