使用动态库时未定义的引用问题

时间:2010-08-05 02:44:51

标签: c++ dll shared-libraries

我正在阅读静态和动态库。为了探索更多内容,我创建了三个文件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时一切顺利,为什么?

我哪里错了?

1 个答案:

答案 0 :(得分: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