繁体   English   中英

对extern类的未定义引用?

[英]Undefined reference to extern class?

当在类上使用extern时,它给了我未定义的引用,但是当我创建函数时,我从该类调用“static”它工作正常。

无论如何不使用静态成员函数吗?

我的测试代码:

#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;

(并假设分配它)。

首先实例化一个实例,并确保在目标文件中有一个非externg_myClass定义。

什么可以是extern是对象,而不是cass。 这里缺少的是你声明extern的对象的定义。

你应该做 :

extern MyClass *g_myClass; // where you want to expose the existence of g_myClass, often in a header


MyClass *g_myClass; // the real definition of your object, in one (and only one) compilation unit  (cpp file).

第一个声明对象,第二个声明它。 在您的示例中,您声明对象存在而不在任何位置定义它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM