编译dll
方法一:
共有三个文件:print.h,print.c,test.c
print.h: 文件内容
ifndef PRINT_H
define PRINT_H
ifdef __cplusplus
extern " C " {
endif
//打印点东西 void Print(int iNum);
ifdef __cplusplus
}
endif
endif
print.c: 文件内容
include
include "print.h"
void Print(int iNum) { switch(iNum) { case 1: printf("hello,this is 1/n"); break; case 2: printf("ok ,2 now/n"); break; default: printf("hihi,default now /n"); break; } getch(); return; }
test.c:文件内容
include
include "print.h"
int main() { printf("please print a num:/n"); int iNum = -1; scanf("%d", &iNum); Print(iNum); return 1; }
编译动态dll库:
gcc -Wall -shared print.c -o print.dll
或者
gcc --share print.c -o print.dll
调用dll库生成exe文件:
gcc test.c print.dll -o test
编译静态库,可供windows调用:
1、gcc -shared -o print.dll print.c -Wl,--output-def,print.def,--out-implib,libprint.a
2、lib /machine:i386 /def:print.def
调用:vs2005
main.c
include
include
include "print.h"
pragma comment(lib,"print.lib")
int main() { Print(1); system("pause");
return 0;
}
方法二:
两个文件:Foo.c 和 Foo_test.c
Foo.c:文件内容
include
include
// 这就是按需加载的dll的主函数,dll被加载、卸载时,系统都回调用这个函数,通过dwReason判断 BOOL WINAPI DllMain(HINSTANCE hModule, DWORD dwReason, LPVOID lpvReserved) { switch(dwReason) { // 如果是进程加载本dll case DLL_PROCESS_ATTACH: printf("process attach/n"); break; // 如果是进程卸载本dll case DLL_PROCESS_DETACH: printf("thread attach/n"); break; // 如果是线程加载本dll case DLL_THREAD_ATTACH: printf("thread attach/n"); break; // 如果是线程卸载本dll case DLL_THREAD_DETACH: printf("process attach/n"); break; } // 如果返回FALSE,则说明加载失败,不会继续被加载,也不可使用 return TRUE; }
int foo(char *str) { printf("%s/n", str); return 0; }
Foo_test.c:文件内容
include
include
typedef int (FOO)(char str);
int main() { HMODULE mod; FOO foo;
mod = LoadLibrary("lib.dll");
printf("from main/n");
if((foo = (FOO)GetProcAddress(mod, "foo")) != NULL) {
foo("hello world");
}
FreeLibrary(mod);
getch();
return 0;
}
编译动态dll库:
gcc -Wall -shared Foo.c -o Foo.dll
或者
gcc --share Foo.c -o Foo.dll
调用dll库生成exe文件:
gcc Foo_test.c Foo.dll -o Foo_test
资料:
1、基于MSYS的Win32动态链接库DLL开发:http://code.google.com/p/msys-cn/wiki/Chapter5
发表评论