linux
动态的头文件api.h
#ifndef _API_H#define _API_H#ifdef DLL_IMPLEMENT#define DLL_EXPORT extern "C"#else#define DLL_EXPORT#endifDLL_EXPORT int mysum(int a, int b);#endif // _API_H
动态库的源文件api.cpp
#define DLL_IMPLEMENT#include "api.h"#includeDLL_EXPORT int mysum(int a, int b){ std::cout << "This (mysum) is a c++ function." << std::endl; return a + b;}
调用动态库的测试代码main.c
#include#include "api.h"int main(){ int sum = mysum(8, 3); printf("The sum is %d\n", sum);}
下面在命令行测试:
g++ -shared -fPIC -o libmyapi.so api.cpp #生成动态库gcc main.c -o a.out -L. -lmyapi #链接动态库生成执行文件ln -s /path/to/libmyapi.so /usr/lib/libmyapi.so #在系统的动态库搜索路径建立软连接ldconfig #让系统重新搜索一遍动态库./a.out #执行,下面是输出 This (mysum) is a c++ function. The sum is 11
windows
动态的头文件api.h
#ifndef _API_H#define _API_H#ifdef DLL_IMPLEMENT#define DLL_EXPORT extern "C" __declspec(dllexport)#else#define DLL_EXPORT extern "C" __declspec(dllimport)#endif#define MYAPI __stdcallDLL_EXPORT int MYAPI mysum(int a, int b);#endif // _API_H
动态库的源文件api.cpp
#define DLL_IMPLEMENT#include "api.h"#includeint MYAPI mysum(int a, int b){ std::cout << "This (mysum) is a c++ function." << std::endl; return a + b;}
调用动态库的测试代码main.c
#include#include "api.h"#pragma comment(lib, "./myapi.lib")int main(){ int sum = mysum(8, 3); printf("The sum is %d\n", sum);}
windows在visual studio中测试即可
over