gpt4 book ai didi

c++ - 使用动态库时 undefined reference 问题

转载 作者:太空狗 更新时间:2023-10-29 23:09:52 26 4
gpt4 key购买 nike

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

我哪里错了?

最佳答案

在为 .so(或您所说的 .dll)编译代码时,该代码需要与位置无关。人海合会:

   -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

关于c++ - 使用动态库时 undefined reference 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3411407/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com