繁体   English   中英

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

[英]Undefined reference problem when dynamic library is used

我正在阅读有关静态和动态库的内容。 为了探索更多,我创建了三个文件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;
}

现在我使用g++ -c demo.cppg++ -c main.cpp创建了两个目标文件: demo.omain.o ,然后使用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一切顺利,为什么?

我哪里错了?

在编译.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

暂无
暂无

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

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