g++简单的编译生成动态链接文件 动态库调用

一个最简单的动态链接库程序,使用g++命令行编译。便于回忆,就把它记到Blog中。

编译成obj文件:

g++ -c -o dll.obj dll.cpp

链接obj,生成dll:

g++ -shared -o dll.so dll.obj

1
2
3
4
5
6
7
8
9
10
11
 

#define __dll_h__
#ifdef __MY_DLL_LIB__
#define DLL_EXPORT extern "C" __declspec(dllexport)
#else
#define DLL_EXPORT extern "C" __declspec(dllimport)
#endif

DLL_EXPORT int (int x, int y);
#endif
1
2
3
4
5
6
7
/* file: dll.cpp */ 
#define __MY_DLL_LIB__
#include "dll.h"
int (int x, int y)
{
return x > y ? x : y;
}

动态库调用

调用动态库:
直接编译成exe:

g++ main.cpp dll.so -o main.exe

1
2
3
4
5
6
7
8
9
10
11
12
/* file: main.cpp */ 
#include "dll.h"
#include <iostream>
using namespace std;
int main()
{
int a = 2;
int b = 4;
cout << mymax(a, b) << endl;

return 0;
}