linux
动态的头文件api.h
#ifndef _API_H
#define _API_H #ifdef DLL_IMPLEMENT
#define DLL_EXPORT extern "C"
#else
#define DLL_EXPORT
#endif DLL_EXPORT int mysum(int a, int b); #endif // _API_H
动态库的源文件api.cpp
#define DLL_IMPLEMENT #include "api.h"
#include <iostream> DLL_EXPORT int mysum(int a, int b)
{
std::cout << "This (mysum) is a c++ function." << std::endl;
return a + b;
}
调用动态库的测试代码main.c
#include <stdio.h>
#include "api.h" int main()
{
int sum = mysum(, );
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 __stdcall DLL_EXPORT int MYAPI mysum(int a, int b); #endif // _API_H
动态库的源文件api.cpp
#define DLL_IMPLEMENT #include "api.h"
#include <iostream>int MYAPI mysum(int a, int b)
{
std::cout << "This (mysum) is a c++ function." << std::endl;
return a + b;
}
调用动态库的测试代码main.c
#include <stdio.h>
#include "api.h"
#pragma comment(lib, "./myapi.lib") int main()
{
int sum = mysum(, );
printf("The sum is %d\n", sum);
}
windows在visual studio中测试即可
over