现在的位置: 首页 > 综合 > 正文

gcc编译dll和调用dll

2013年10月09日 ⁄ 综合 ⁄ 共 1862字 ⁄ 字号 评论关闭
方法一:

共有三个文件: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 <stdio.h>
#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 <stdio.h>
#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 <stdio.h>
#include <stdlib.h>
#include "print.h"
#pragma comment(lib,"print.lib")

int main()
{
    Print(1);
 system("pause");
    
    return 0;
}

 方法二:

两个文件:Foo.c 和 Foo_test.c

***************************************************************

Foo.c:文件内容

#include <windows.h>
#include <stdio.h>

// 这就是按需加载的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:
               

抱歉!评论已关闭.