在工作过程中,其他人给我的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;
}