因為機子上沒有安裝Visual Studio,所以找到了一種通過code::blocks編譯dll的方式,踩到的坑是code::blocks默認的compiler是32位的,這樣編譯出的dll也是32位的,編譯64位的需要借助MinGW-w64的toolchain。
為code::blocks配置外部MinGW-w64編譯器可以參考Compile 64-bit under windows with MinGW-w64。
使用code::blocks創建一個dll的工程,如下圖:

go和next到下一步:

選擇我們上面配置的編譯器:

Finsh完成,此時已經建好main.h和main.cpp文件,這里我實現了一個add函數的dll庫,代碼如下:
#ifndef __MAIN_H__ #define __MAIN_H__ #include <windows.h> /* To use this exported function of dll, include this header * in your project. */ #ifdef BUILD_DLL #define DLL_EXPORT __declspec(dllexport) #else #define DLL_EXPORT __declspec(dllimport) #endif #ifdef __cplusplus extern "C" { #endif int DLL_EXPORT add(int a, int b); #ifdef __cplusplus } #endif #endif // __MAIN_H__
main.cpp
// a sample exported function int DLL_EXPORT add(int a, int b) { return a + b; } extern "C" DLL_EXPORT BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH: // attach to process // return FALSE to fail DLL load break; case DLL_PROCESS_DETACH: // detach from process break; case DLL_THREAD_ATTACH: // attach to thread break; case DLL_THREAD_DETACH: // detach from thread break; } return TRUE; // succesful }
build之后就可以生成我們想要的dll庫。這里剛開始沒發現compiler位數問題,編譯出的是32位的dll,在x86_64平台上用會報錯,通過使用Cygwin命令行仿真工具的file命令可以查看dll的位數,這個是比較簡單的判斷dll位數的方式。
這里在安裝MingGW-w64 toolchain時也遇到一個問題,就是使用上述鏈接提供的MinGW下載鏈接下載的mingw-w64-installer.exe安裝時會報"cannot download repository.list"的錯誤,所以又找了下發現這個錯誤還挺多人碰到過,官方沒有修復而是給出編譯好的版本,可以在這里下載,下載完解壓出來就可以使用了。
關於使用編譯好的dll庫可以參考:Windows環境下創建並使用動態鏈接庫(CodeBlocks版),另外還可以使用code::blocks編譯和使用靜態庫:CodeBlocks創建靜態鏈接庫和使用
