【发布时间】:2009-08-24 15:25:49
【问题描述】:
我在 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++ 链接器 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: 未定义对
loglevel' /home/hilboll/src/libiup/Release/libiup.so: undefined reference toerrormsg' 的引用 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': 新定义 z:\src\libiup\src\stratcalc../interp/SimpleInterpolator.h(16): Siehe Deklaration von 'errormsg' z:\src\vs\libiup_dll\libiup_dll.h(234) : 错误 C2086: 'int loglevel': 新定义 z:\src\libiup\src\stratcalc../interp/SimpleInterpolator.h(17): Siehe Deklaration von 'loglevel'
据我了解,这意味着 VS 认为我将这两个变量定义了两次。但是,在 SimpleInterpolator.h 16/17 中,只有 extern 声明...
似乎我还没有理解全局变量是如何工作的。非常感谢任何帮助!
【问题讨论】:
-
使用会说英语的编译器可能是一个好的开始。
-
显示实际来源而不是描述它会很好。
标签: c++ shared-libraries global-variables