【发布时间】:2020-04-11 11:10:03
【问题描述】:
我正在尝试在 Ubuntu 中用 C++ 构建一个共享库(我将在运行时使用 dlopen 加载它),但我注意到即使缺少一些依赖项,共享库也能正常构建。如果我要构建一个可执行文件,我会收到一个undefined reference 链接器错误,这是我想在这里看到的。
此示例中的细节可能有点过多,但我不完全确定如何减少它并使其具有代表性。
Base.h
class Base{
public:
virtual void foo()=0;
};
extern "C" {
Base* CreateBase();
}
extern "C" {
void DestroyBase(Base* b);
}
派生的.h
#include "Base.h"
class Derived : public Base {
public:
void foo();
};
extern "C" {
Base* CreateBase() {
return new Derived;
}
}
extern "C" {
void DestroyBase(Base* b) {
delete b;
}
}
派生的.cc
#include "Derived.h"
#include "OtherClass.h"
#include <iostream>
void Derived::foo(){
std::cout << "Derived::foo()" << std::endl;
std::cout << "Calling OtherClass::bar()" << std::endl;
OtherClass other;
other.bar();
}
OtherClass.h
class OtherClass{
public:
void bar();
};
我构建共享库的命令行是
g++ -shared -fPIC -o libtest_dll.so Derived.cc
问题是我没有定义Derived::foo() 调用的OtherClass::bar(),但是libtest_dll.so 构建时没有错误或警告。我的理解是,在 Windows 的 Visual Studio 中,如果我用这段代码构建一个 DLL,它将无法链接。如何在 Ubuntu/Linux 中使用 g++ 获得这种行为?
在 Ubuntu 19.04 上运行 g++ 8.3.0-6
【问题讨论】:
-
当然没问题。运行任何工具进行共享对象检查,您会发现该符号将被标记为运行时依赖项。
ldd libtest_dll.so应该显示依赖关系。 -
@0andriy 这个想法是
OtherClass::bar()应该在这个源代码中,但是我不小心把它漏掉了。我不想在运行时找到它,而是想在编译时找到它。
标签: c++ linux linker shared-libraries