对于类 unix 操作系统(Linux、MacOS 等),静态库 表示
目标文件的ar archive。 ar 是 GNU 通用
目的存档器。它不关心您将哪种文件放入存档中。它是
当它们碰巧是目标文件时,只是习惯将其称为“静态库”。和
将ar 存档称为*.a 也只是一种习惯。你可以叫它
*.lib,或任何东西。
对于 Visual Studio,静态库 表示 PE 格式目标文件的存档
通常由微软工具LIB创建。
Microsoft LIB 存档的格式实际上与 Unix ar 存档的格式相同。微软
很久以前就采用了。
因此,如果您在 Linux 上使用发行版的 PE 交叉编译器编译一些 PE 对象文件
然后将它们归档到 *.lib 和 ar 中,你就拥有了一个可以在 Windows 中使用的静态库
使用 Visual Studio 编译器。
好吧,只要那些目标文件有 C 二进制接口,你就可以。
如果它们中的任何一个具有 C++ 接口,它们就毫无用处:Microsoft 和 GCC C++ 编译器使用不同的名称修饰协议,否则 ABI 不兼容。
演示
我们从 linux 开始,使用一些静态库的源代码:
hello.c
#include <stdio.h>
void hello(void)
{
puts("Hello world");
}
交叉编译:
$ x86_64-w64-mingw32-gcc-win32 -o hello.obj -c hello.c
制作静态库:
$ ar rcs hello.lib hello.obj
然后是一个将与hello.lib链接的程序:
main.c
extern void hello(void);
int main(void)
{
hello();
return 0;
}
现在我们跳到一个 Windows 10 虚拟机,我们正在查看我们拥有的文件
刚刚通过共享文件夹创建:
E:\develop\so\xstatlib>dir
Volume in drive E is VBOX_imk
Volume Serial Number is 0000-0804
Directory of E:\develop\so\xstatlib
03/12/2017 18:37 72 main.c
03/12/2017 18:29 978 hello.lib
03/12/2017 18:26 66 hello.c
03/12/2017 18:27 832 hello.obj
4 File(s) 1,948 bytes
0 Dir(s) 153,282,871,296 bytes free
编译并链接我们的程序:
E:\develop\so\xstatlib>cl /Fehello.exe main.c hello.lib
Microsoft (R) C/C++ Optimizing Compiler Version 19.11.25547 for x64
Copyright (C) Microsoft Corporation. All rights reserved.
main.c
Microsoft (R) Incremental Linker Version 14.11.25547.0
Copyright (C) Microsoft Corporation. All rights reserved.
/out:hello.exe
main.obj
hello.lib
运行它:
E:\develop\so\xstatlib>hello
Hello world