如何在 Linux 或 Macos 中为 Windows 编译静态 .lib 库

How to compile static .lib library for Windows in Linux or Macos

我正在寻找在 Linux 或 Macos 中为 Windows 编译静态库的方法,似乎有交叉编译器可以为 Windows 生成 .a 库,例如 this one,但这不是我想要的,我想要的是 Windows,最好是 Visual Studio 的 .lib 静态库文件。我知道我可以 运行 一个 Windows 虚拟机并使用 Visual Studio,但这太重了,无法在命令行中完成。

对于类 unix 操作系统(Linux、MacOS 等),静态库 意味着 ar archive 个目标文件。 ar是GNU将军 目的存档器。它不在乎您将哪种文件粘贴到存档中。它是 当它们碰巧是目标文件时,只是习惯称它为 "a static library" 。和 ar 档案被称为 *.a 也只是一个习惯。你可以称它为 *.lib,或任何东西。

对于Visual Studio,静态库表示PE格式目标文件的归档 通常由 Microsoft 工具 LIB.

创建

Microsoft LIB 存档的格式实际上与 Unix ar 存档的格式相同。微软 很久很久以前就采用了它。

因此,如果您使用发行版的 PE 交叉编译器在 Linux 上编译一些 PE 目标文件 然后用 ar 将它们归档到 *.lib 中,你就得到了一个可以放入 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

然后一个程序将被link编辑为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

编译并link我们的程序:

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