我在 C++ 共享库项目中遇到全局变量问题。我的库必须作为标准 g++ 共享库 (.so) 以及 dll 工作。我通过创建文件 libiup_dll.cpp 和 libiup_dll.h 来做到这一点,我有类似的东西
#ifdef BUILD_DLL
// code for the dll: wrapper functions around the classes in my shared library
#endif
在我的 dll 中,我需要函数 setloglevel(int) 和 geterrormsg()。在我的所有课程中,我会将所有错误消息附加到全局变量 errormsg 中。然后应该由 geterrormsg() 函数返回此变量。我通过使用实现了这一点
std::string errormsg;
int loglevel;
在 libiup_dll.h (外部和#ifdefs,所以它应该是全局可用的),然后把
extern std::string errormsg;
extern int loglevel;
在我的班级的 .h 文件中(在班级之外,在文件的顶部)
现在我有两个问题:
1) 使用我的库使用 g++ 编译命令行程序时,出现错误
构建目标:libiup_test 调用:GCC C++ Linker g++ -L"/home/hilboll/src/libiup/Release" -L/usr/local/lib -o"libiup_test" ./src/stratcalc/SimpleStratosphericColumnCalculatorTest.o ./src/ interp/SimpleInterpolatorTest.o ./src/Test.o -lgsl -lhdf5 -lhdf5_cpp -lblas -liup /home/hilboll/src/libiup/Release/libiup.so: undefined reference to
loglevel' /home/hilboll/src/libiup/Release/libiup.so: undefined reference to
errormsg' collect2: ld 返回 1 退出状态 make : *** [libiup_test] 错误 1
即使在我的命令行程序中,也没有任何对 errormsg 或 loglevel 的引用。
2)当试图用VS2008在windows下编译dll时,我得到了
z:\src\vs\libiup_dll\libiup_dll.h(229) : 错误 C2086: 'std::string errormsg': Neudefinition z:\src\libiup\src\stratcalc../interp/SimpleInterpolator.h(16): Siehe Deklaration von 'errormsg' z:\src\vs\libiup_dll\libiup_dll.h(234) : error C2086: 'int loglevel': Neudefinition z:\src\libiup\src\stratcalc../interp/SimpleInterpolator.h( 17): Siehe Deklaration von 'loglevel'
据我了解,这意味着 VS 认为我将这两个变量定义了两次。但是,在 SimpleInterpolator.h 16/17 中,只有 extern 声明......
似乎我还没有理解全局变量是如何工作的。任何帮助是极大的赞赏!