using dynamic library in c++

本文介绍了如何在Windows和Linux平台上编写和使用动态链接库(DLL)。在Windows中,通过VS2008创建DLL项目并导出函数;在Linux中,使用Makefile构建共享库并在其他项目中链接。两种平台的实现方式有所不同。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

when we use c++ , we always need write many library code so that we can use it in many places. in the article, i will introduce how to write and use dynamic library in windows and linux.

 

1 . First i will introduce dll technique in the windows platform.

 

A. it is very easy to write a dll file. first build a dll project in the vs2008 and write code like this:

 

    extern "C" __declspec(dllexport) int max(int a , int b);

 

    compile the project and we can find .dll and .lib file in the debug directory.

 

B.  next step is using dll in our project.

 

     build another test project. create a new and in the file write code like this:

 

     extern "C" __declspec(dllimport) int max(int a, int b);

 

     if we use vs2008 then we should add .lib file the project property or we can use the instruction as following:

 

     #pragma comment(lib,"libname.lib");

 

     and that's all we should do . it is very easy as i said above.

 

2. now i wll introduce how to use lib in the linux platform

 

    dll is only available in the windows platform, so we can not write a dll project in the linux.

 

    But we can use lib in the linux. it is very easy to write a lib in the linux. much easier than in the windows.

 

    in the lib project functions are not required to add __declspec(dllexport)

 

    But in the makefile we should indicate that the output file is a library object.

 

    $(CC) -shared -Wl,-soname,lib$(name).so.$(majorVersion) $(LDFLAGS) -o $@ $^

 

    the sentence above means the output file a  shared library object and name is lib$(name).so.$(majorVersion)

 

    when we want to use this library object file in the other linux project, we can write the following sentence in the makfile

 

    $(CC) -o $@ $^ $(LDFLAGS) -lTcpServer2 -L $(libdir)/build/linux

 

    -lTcpServer2 means we can to link dynamic library named as TcpServer2, the file name maybe libTcpServer2.so and searching directory is in the $(libdir)/buidl/linxu

 

    we don't do anything else.everything is done.

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值