我正在尝试为 C++ 课程编写一个小型类库。

我想知道是否可以在我的共享对象中定义一组类,然后直接在演示该库的主程序中使用它们。其中有没有什么技巧呢?我记得很久以前(在我开始真正编程之前)读过这篇文章,C++ 类只能与 MFC .dll 一起使用,而不能与普通的 .dll 一起使用,但这只是 Windows 方面。

有帮助吗?

解决方案

C++ 类在 .so 共享库中工作正常(它们也可以在 Windows 上的非 MFC DLL 中工作,但这并不是您真正的问题)。它实际上比 Windows 更容易,因为您不必从库中显式导出任何符号。

本文档将回答您的大部分问题: http://people.redhat.com/drepper/dsohowto.pdf

要记住的主要事情是使用 -fPIC 编译时的选项,以及 -shared 链接时的选项。您可以在网上找到很多示例。

其他提示

我的解决方案/测试

这是我的解决方案,它达到了我的预期。

代码

猫.hh :

#include <string>

class Cat
{
    std::string _name;
public:
    Cat(const std::string & name);
    void speak();
};

猫.cpp :

#include <iostream>
#include <string>

#include "cat.hh"

using namespace std;

Cat::Cat(const string & name):_name(name){}
void Cat::speak()
{
    cout << "Meow! I'm " << _name << endl;
}

主程序 :

#include <iostream>
#include <string>
#include "cat.hh"

using std::cout;using std::endl;using std::string;
int main()
{
    string name = "Felix";
    cout<< "Meet my cat, " << name << "!" <<endl;
    Cat kitty(name);
    kitty.speak();
    return 0;
}

汇编

首先编译共享库:

$ g++ -Wall -g -fPIC -c cat.cpp
$ g++ -shared -Wl,-soname,libcat.so.1 -o libcat.so.1 cat.o

然后使用库中的类编译主可执行文件或 C++ 程序:

$ g++ -Wall -g -c main.cpp
$ g++ -Wall -Wl,-rpath,. -o main main.o libcat.so.1 # -rpath linker option prevents the need to use LD_LIBRARY_PATH when testing
$ ./main
Meet my cat, Felix!
Meow! I'm Felix
$

据我了解,只要链接全部使用同一编译器编译的 .so 文件,就可以了。不同的编译器以不同的方式破坏符号,并且将无法链接。

这是在 Windows 上使用 COM 的优点之一,它定义了将 OOP 对象放入 DLL 中的标准。我可以使用 GNU g++ 编译 DLL,并将其链接到使用 MSVC 甚至 VB 编译的 EXE!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top