2010-08-05 141 views
3

我正在閱讀有關靜態和動態庫的信息。要探索更多,我創建三個文件2 .cpp文件和1個.h文件使用動態庫時未定義的引用問題

demo.h

class demo 
{ 

    int a; 

    public: 

    demo(); 
    demo(const demo&); 
    demo& operator=(const demo&); 
    ~demo(); 
}; 

demo.cpp

#include "demo.h" 
#include <iostream> 
demo::demo():a() 
{ 
    std::cout<<"\nInside default constructor\n"; 
} 

demo::demo(const demo&k) 
{ 

    this->a=k.a; 
    std::cout<<"\nInside copy constructor\n"; 
} 

demo& demo::operator=(const demo&k) 
{ 
    this->a=k.a; 
    std::cout<<"\nInside copy assignment operator\n"; 
    return *this; 
} 

demo::~demo() 
{ 
    std::cout<<"\nInside destructor\n"; 
} 

main.cpp

#include "demo.h" 

int main() 
{ 

    demo d; 
    demo d1=d; 
    demo d2; 
    d2=d; 
} 

現在我創建兩個目標文件:demo.omain.o使用g++ -c demo.cppg++ -c main.cpp,然後創建使用ar cr demo.a demo.o main.o

我還創建使用g++ -shared demo.o main.o -o demo.dll

一個動態庫,現在,當我用我的靜態庫(g++ demo.a -o demo)創建可執行的一切靜態庫一切順利。但是當我使用我的動態庫創建可執行文件時,出現錯誤Undefined reference to main 我已經使用以下命令來創建可執行文件g++ demo.dll -o demo

當我使用g++ main.cpp -o demo demo.dll一切都很好,爲什麼?

我在哪裏錯了?

+0

這對我的作品。你可以發佈你的makefile,如果你使用一個?當你試圖從一個共享庫,比如helloWorld或者'int main(){return(0);}'來做更簡單的事情時會發生什麼呢? – Beta 2010-08-05 04:28:05

回答

1

編譯.so(或您稱之爲.dll)的代碼時,代碼需要與位置無關。男人GCC:

-shared 
     Produce a shared object which can then be linked with other objects 
     to form an executable. Not all systems support this option. For 
     predictable results, you must also specify the same set of options 
     that were used to generate code (-fpic, -fPIC, or model suboptions) 
     when you specify this option. 

    ... 

    -fpic 
     Generate position-independent code (PIC) suitable for use in a 
     shared library, if supported for the target machine. Such code 
     accesses all constant addresses through a global offset table 
     (GOT). The dynamic loader resolves the GOT entries when the 
     program starts (the dynamic loader is not part of GCC; it is part 
     of the operating system). If the GOT size for the linked 
     executable exceeds a machine-specific maximum size, you get an 
     error message from the linker indicating that -fpic does not work; 
     in that case, recompile with -fPIC instead. (These maximums are 8k 
     on the SPARC and 32k on the m68k and RS/6000. The 386 has no such 
     limit.) 

     Position-independent code requires special support, and therefore 
     works only on certain machines. For the 386, GCC supports PIC for 
     System V but not for the Sun 386i. Code generated for the IBM 
     RS/6000 is always position-independent. 

     When this flag is set, the macros "__pic__" and "__PIC__" are 
     defined to 1. 

換句話說:

g++ -o main.o -c -fpic main.cpp 
g++ -o demo.o -c -fpic demo.cpp 
g++ -o demo.dll -shared main.o demo.o 
g++ -o demo demo.dll