C编写的动态库dll C++调用

                在工作过程中,其他人给我的C动态库,我用C++调用老是失败,所以做个试验验证一下写的方式,直接上代码

//add.h
#ifndef C_LIB_H
#define C_LIB_H


#define DLLExport __declspec(dllexport)

#ifdef __cplusplus
extern "C"{
#endif

   DLLExport int  add(int x,int y);

#ifdef __cplusplus
   }
#endif


#endif

//add.c
#include "add.h"
int add( int x, int y )
{
    return x + y;
}

//sub.h
#ifndef C_LIB_H
#define C_LIB_H


#define DLLExport __declspec(dllexport)

#ifdef __cplusplus
extern "C"{
#endif

    DLLExport int  sub(int x,int y);

#ifdef __cplusplus
}
#endif


#endif

//sub.c
#include "sub.h"
int sub( int x, int y )
{
    return x - y;
}
分开写是为了验证两个接口分在不同的头文件和源文件当中,怎么把这两个接口合并到一个DLL当中。

方法如下:

        第一,先分别单独编译这两个源文件得到 add.obj sub.obj

        第二,自己手动链接这两个obj文件,命令方式如下:link /DLL /OUT:test.dll add.obj sub.obj

这样就合并了这两个接口方法到test.dll当中。


C++ 调用方式如下:

#include "add.h"
#include "sub.h"
#include <stdio.h>

extern "C" int __declspec(dllimport) sub(int x,int y);
extern "C" int __declspec(dllimport) add(int x,int y);

int main()
{
    int result = add(2,3);
    printf("%d\n",result);
    result = sub(3, 2);
    printf("%d",result);
    getchar();
    return 0;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值