【问题标题】:How to compile static .lib library for Windows in Linux or Macos如何在 Linux 或 Macos 中为 Windows 编译静态 .lib 库
【发布时间】:2017-12-04 16:27:55
【问题描述】:

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

【问题讨论】:

    标签: c linux windows macos static-libraries


    【解决方案1】:

    对于类 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链接的程序:

    ma​​in.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
    

    【讨论】:

    • extern "C" 怎么样?这是否有助于 gcc/VisualStudio 在 C++ 名称修改方面的兼容性?
    • @BarmakShemirani 是的,当然,extern "C" 范围内的 API 首先必须是有效的 C API。我使措辞更准确。
    • 非常感谢您提供如此详细的解释和示例,非常感谢。
    • 相反呢?生成一个在 Windows 中有效的 macOS 静态库?
    • @Royi 你的意思是this question。您根本无法使用 MSVC 创建 Linux 二进制文件。 MSVC 生成 Microsoft PE/COFF 格式的二进制文件。 Linux 二进制文件是 ELF 格式。粉笔和奶酪。您只能通过 cross-compiling in a Unix-like environment under Windows 在 Windows 上构建 ELF 二进制文件,或者通过在 Linux VM 或 WSL 中构建。上面的答案描述了交叉编译 Linux -> Windows。
    猜你喜欢
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    • 2010-10-16
    相关资源
    最近更新 更多