我记得有一种比较老式的方法是使用一个DEF文件来表明哪些函数是用来导出的,现在已经多不用该方式,而是使用__declspec(dllexport)的关键字。
下边展示一种老方式的:
/*第一个文件 x.h*/
#include <stdio.h>
int print(int a);
/*第二个文件 x.c*/
#include "x.h"
int print(int i)
{
printf("%d/n", i);
return 0;
}
/*DEF文件 x.def*/
EXPORTS
print
命令行编译的时候使用:cl /LD x.c x.def,在命令行会显示:
/out:x.dll
/dll
/implib:x.lib
/def:x.def
x.obj
正在创建库 x.lib 和对象 x.exp
如果没有将def文件加上,就会是:
/out:x.dll
/dll
/implib:x.lib
x.obj
生成的dll文件使用Dependency Viewer看不到有任何导出来的方法,并且没有生成EXP文件和LIB文件。然后使用如下的代码就可以调用:
/*test.c*/
#include "x.h"
int main(int argc, char *argv[])
{
printf("%d/n", print(100));
return 0;
}
命令行:cl test.c /link x.lib
接下来展示新方式:
/*第一个文件 x.h*/
#include <stdio.h>
__declspec(dllexport) int x();
/*第二个文件 x.c*/
#include "x.h"
int x()
{
printf("hello world/n");
return 0;
}
命令行: cl /LD a.c,生成了lib文件、dll文件、exp文件
/*test.c*/
#include "x.h"
int main(int argc, char *argv[])
{
printf("%d/n", x());
return 0;
}
编译之后能够正常运行。这种方式中 x.c文件的方法可以添加__declspec(dllexport) 限制,也可以不添加,没影响。但是如果头文件里边没有这个限制,编译出来的dll文件就没有导出方法,不会生成lib和exp文件。如果仅在C文件中添加了,其结果就是编译是编译报告方法重定义问题。
如果编译生成DLL和Lib之后将头文件中的__declspec(dllexport)去掉,然后将头文件和lib、dll一起发布,是可以使用test.c引用的,并且能够编译出正确的程序并运行。