由dll导出lib文件

  老生长谈的问题了,网上的教程也很多,这里以实际例子作个备份,并说明下注意点。

  只有dll文件(my.test.dll)和头文件,没有lib文件,需要导出lib,静态编译进代码中,用VS自带的dumpbin.exe和lib.exe来完成。

  dumpbin.exe和lib.exe的路径不赘述,路径见下图:

 由dll导出lib文件_第1张图片

  先用如下命令行导出dll的相关信息:

dumpbin /exports my.test.dll > my.test.def
  导出的my.test.def文件内容如下:
Microsoft (R) COFF Binary File Dumper Version 6.00.8447
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.


Dump of file my.test.dll

File Type: DLL

  Section contains the following exports for testdll.dll

           0 characteristics
    587C3C7E time date stamp Mon Jan 16 11:22:38 2017
        0.00 version
           1 ordinal base
           4 number of functions
           4 number of names

    ordinal hint RVA      name

          1    0 0000113C ??0CTestdll@@QAE@XZ
          2    1 00001000 ??4CTestdll@@QAEAAV0@ABV0@@Z
          3    2 00001127 ?fnTestdll@@YAHXZ
          4    3 0000318C ?nTestdll@@3HA

  Summary

        1000 .data
        1000 .rdata
        1000 .reloc
        1000 .text

  然后,修改my.test.def文件如下:
LIBRARY my.test.dll 
EXPORTS 
??0CTestdll@@QAE@XZ @1 
??4CTestdll@@QAEAAV0@ABV0@@Z @2 
?fnTestdll@@YAHXZ @3 
?nTestdll@@3HA @4 

  实际测试,后面也可以不带“@数字”,或者如下:

LIBRARY my.test.dll 
EXPORTS 
??0CTestdll@@QAE@XZ
??4CTestdll@@QAEAAV0@ABV0@@Z
?fnTestdll@@YAHXZ
?nTestdll@@3HA

  注意,以上内容中LIBRARY后面一定要是dll文件的文件名。如果文件名(不含后缀)中还带有“.",则需要把最后的.dll带上。比如此例中文件全名为my.test.dll, 则LIBRARY后面一定要写my.test.dll,否则调用程序编译链接后,运行时会提示找不到my.test。如果文件全名为test.dll,则LIBRARY后可写test.dll,也可写test。

  然后用以下命令行制作lib文件,即可生成lib文件:

lib /def:my.test.def /machine:ix86 /out:my.test.lib

  How to generate an import library (LIB-file) from a DLL?这里有人制作了一个批处理文件,我修改了一下,可以直接使用,批处理文件名为《dll2lib.bat》,直接调用命令dll2lib.bat 32 my.test.dll即可。

@echo off
echo Usage: dll2lib [32^|64] some-file.dll
echo.
echo Generates some-file.lib from some-file.dll, making an intermediate
echo some-file.def from the results of dumpbin /exports some-file.dll.
echo Currently must run without path on DLL.
echo (Fix by removing path when of lib_name for LIBRARY line below?)
echo.
echo Requires 'dumpbin' and 'lib' in PATH - run from VS developer prompt.
echo.
echo Script inspired by http://stackoverflow.com/questions/9946322/how-to-generate-an-import-library-lib-file-from-a-dll
echo.
echo.
SETLOCAL
if "%1"=="32" (set machine=x86) else (set machine=x64)
set dll_file=%2
set dll_file_no_ext=%dll_file:~0,-4%
set exports_file=%dll_file_no_ext%-exports.txt
set def_file=%dll_file_no_ext%.def
set lib_file=%dll_file_no_ext%.lib
set lib_name=%dll_file_no_ext%

dumpbin /exports %dll_file% > %exports_file%

echo LIBRARY %lib_name%.dll > %def_file%
echo EXPORTS >> %def_file%
for /f "skip=19 tokens=1,4" %%A in (%exports_file%) do if NOT "%%B" == "" (echo %%B @%%A >> %def_file%)

lib /def:%def_file% /out:%lib_file% /machine:%machine%

REM Clean up temporary intermediate files
del %exports_file% %def_file% %dll_file_no_ext%.exp


你可能感兴趣的:(由dll导出lib文件)