Fla*_*ame 9 c++ linux class-library
我正在尝试为C++课程编写一个小类库.
我想知道是否有可能在我的共享对象中定义一组类,然后直接在我的主程序中使用它们来演示库.有任何技巧吗?我记得很久以前(在我开始编程之前)读过这个C++类只能用于MFC .dll而不是普通的,但这只是windows端.
Kri*_*son 13
C++类在.so共享库中工作正常(它们也适用于Windows上的非MFC DLL,但这不是你的问题).它实际上比Windows更容易,因为您不必显式地从库中导出任何符号.
本文档将回答您的大部分问题:http://people.redhat.com/drepper/dsohowto.pdf
要记住的主要事项是-fPIC在编译时使用选项,-shared在链接时使用选项.你可以在网上找到很多例子.
这是我的解决方案,它符合我的预期.
cat.hh:
#include <string>
class Cat
{
std::string _name;
public:
Cat(const std::string & name);
void speak();
};
Run Code Online (Sandbox Code Playgroud)
cat.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;
}
Run Code Online (Sandbox Code Playgroud)
main.cpp:
#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;
}
Run Code Online (Sandbox Code Playgroud)
您首先编译共享库:
$ g++ -Wall -g -fPIC -c cat.cpp
$ g++ -shared -Wl,-soname,libcat.so.1 -o libcat.so.1 cat.o
Run Code Online (Sandbox Code Playgroud)
然后使用库中的类编译主可执行文件或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
$
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18705 次 |
| 最近记录: |