2010-08-05 64 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 
相关问题