在类上使用 extern 时,它会给我 undefined reference ,但是当我创建从该类“静态”调用的函数时,它工作正常。
有没有办法不使用静态成员函数就可以做到这一点?
我的测试代码:
#include <iostream>
class MyClass
{
public:
void print() { std::clog << "print()" << std::endl; }
};
extern MyClass *g_myClass;
int main()
{
g_myClass->print();
return 0;
}
错误:
main.o:main.cpp:(.text+0x129): undefined reference to `_g_myClass'
在实际代码中我遇到了段错误。
回溯:
Program received signal SIGSEGV, Segmentation fault.
0x00465af2 in std::_Rb_tree<Irc::Config::Config_t, std::pair<Irc::Config::Config
_t const, std::string>, std::_Select1st<std::pair<Irc::Config::Config_t const, s
td::string> >, std::less<Irc::Config::Config_t>, std::allocator<std::pair<Irc::C
onfig::Config_t const, std::string> > >::_M_begin (this=0x0)
at c:/qt/2010.04/mingw/bin/../lib/gcc/mingw32/4.4.0/include/c++/bits/stl_tre
e.h:482
482 { return static_cast<_Link_type>(this->_M_impl._M_header._M_parent
); }
(gdb) bt
#0 0x00465af2 in std::_Rb_tree<Irc::Config::Config_t, std::pair<Irc::Config::Co
nfig_t const, std::string>, std::_Select1st<std::pair<Irc::Config::Config_t cons
t, std::string> >, std::less<Irc::Config::Config_t>, std::allocator<std::pair<Ir
c::Config::Config_t const, std::string> > >::_M_begin (this=0x0)
at c:/qt/2010.04/mingw/bin/../lib/gcc/mingw32/4.4.0/include/c++/bits/stl_tre
e.h:482
#1 0x0046596b in std::_Rb_tree<Irc::Config::Config_t, std::pair<Irc::Config::Co
nfig_t const, std::string>, std::_Select1st<std::pair<Irc::Config::Config_t cons
t, std::string> >, std::less<Irc::Config::Config_t>, std::allocator<std::pair<Ir
c::Config::Config_t const, std::string> > >::find (this=0x0, __k=@0x22fe40)
at c:/qt/2010.04/mingw/bin/../lib/gcc/mingw32/4.4.0/include/c++/bits/stl_tre
e.h:1421
#2 0x0045ec7c in std::map<Irc::Config::Config_t, std::string, std::less<Irc::Co
nfig::Config_t>, std::allocator<std::pair<Irc::Config::Config_t const, std::stri
ng> > >::find (this=0x0, __x=@0x22fe40)
at c:/qt/2010.04/mingw/bin/../lib/gcc/mingw32/4.4.0/include/c++/bits/stl_map
.h:659
#3 0x0040d376 in Irc::Config::getInt (this=0x0, arg=1) at configreader.cpp:72
#4 0x00405656 in Irc::Database::connect (this=0x483300) at database.cpp:30
#5 0x00406965 in main (argc=1, argv=0x3d3e18) at main.cpp:26
(gdb)
最佳答案
当你写的时候:
extern MyClass *g_myClass;
您正在声明一个指针。这使编译器可以工作,但链接器也需要它的定义。
您必须在代码中的某处插入:
MyClass *g_myClass;
(并分配它,我想)。
关于c++ - 未定义对外部类的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4276691/