簡體   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