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

Rya*_*yan 6 c linux windows macos static-libraries

我正在寻找方式编译静态库for Windows中的Linux或者MacOS,似乎有交叉编译器生成类似的Windows .A库这一块,但是这不是我想要的,我要的是一个静态的.LIB库文件适用于Windows,最好适用于Visual Studio.我知道我可以运行Windows虚拟机并使用Visual Studio,但这太重了,无法在命令行中完成.

Mik*_*han 8

对于类似Unix的操作系统(Linux,MacOS等),静态库意味着对象文件的ar存档.ar是GNU通用归档器.它并不关心您将哪种文件存入存档.当它们恰好是目标文件时,它就是把它称为"静态库"的习惯.它也只是一个ar被调用的存档的习惯*.a.你可以打电话 *.lib或任何东西.

对于Visual Studio,静态库表示通常由Microsoft工具创建的PE格式对象文件的存档LIB.

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

因此,如果您使用您的发行版的PE交叉编译器在Linux上编译一些PE目标文件,然后将它们存档到一个*.libwith中ar,那么您自己就拥有了一个静态库,可以使用Visual Studio编译器在Windows中运行.

好吧,只要这些目标文件具有C二进制接口,就可以了.如果它们中的任何一个具有C++接口,则它们是无用的:Microsoft和GCC C++编译器使用不同的名称修改协议,否则ABI不兼容.

演示

我们在linux中开始使用静态库的一些源代码:

你好ç

#include <stdio.h>

void hello(void)
{
    puts("Hello world");
}
Run Code Online (Sandbox Code Playgroud)

交叉编译:

$ x86_64-w64-mingw32-gcc-win32 -o hello.obj -c hello.c
Run Code Online (Sandbox Code Playgroud)

制作静态库:

$ ar rcs hello.lib hello.obj
Run Code Online (Sandbox Code Playgroud)

然后一个程序将与以下链接hello.lib:

main.c中

extern void hello(void);

int main(void)
{
    hello();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

现在我们跳进一个Windows 10 VM,我们正在查看我们刚刚通过共享文件夹创建的文件:

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
Run Code Online (Sandbox Code Playgroud)

编译并链接我们的程序:

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
Run Code Online (Sandbox Code Playgroud)

运行:

E:\develop\so\xstatlib>hello
Hello world
Run Code Online (Sandbox Code Playgroud)