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

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


For unix-like OSes (Linux, MacOS, etc) a static library meansan ar archive of object files. ar is the GNU generalpurpose archiver. It doesn't care what kind of files you stick into an archive. It'sjust the custom to call it "a static library" when they happen to be object files. Andit's also just a custom for an ar archive to be called *.a. You can call it*.lib, or anything.

For Visual Studio, a static library means an archive of PE-format object filesusually created by the Microsoft tool LIB.

The format of an Microsoft LIB archive is in fact the same as that of a Unix ar archive. Microsoftjust adopted it, long long ago.

So if you compile some PE object files on Linux using your distro's PE cross-compilerthen archive them into a *.lib with ar, you've got yourself a static library that's good to go in Windowswith the Visual Studio compiler.

Well, you have as long as those object files have C binary interfaces.If any of them have C++ interfaces, they're useless: the Microsoft and GCC C++ compilers use different name-mangling protocols and are otherwise ABI incompatible.

Demo

We start in linux with some source code for the static library:

hello.c

#include <stdio.h>void hello(void){    puts("Hello world");}

Cross-compile:

$ x86_64-w64-mingw32-gcc-win32 -o hello.obj -c hello.c

Make the static library:

$ ar rcs hello.lib hello.obj

Then a program that's going to be linked with hello.lib:

main.c

extern void hello(void);int main(void){    hello();    return 0;}

Now we hop into a Windows 10 VM where we're looking at the the files we'vejust created through a shared folder:

E:\develop\so\xstatlib>dir Volume in drive E is VBOX_imk Volume Serial Number is 0000-0804 Directory of E:\develop\so\xstatlib03/12/2017  18:37                72 main.c03/12/2017  18:29               978 hello.lib03/12/2017  18:26                66 hello.c03/12/2017  18:27               832 hello.obj               4 File(s)          1,948 bytes               0 Dir(s)  153,282,871,296 bytes free

Compile and link our program:

E:\develop\so\xstatlib>cl /Fehello.exe main.c hello.libMicrosoft (R) C/C++ Optimizing Compiler Version 19.11.25547 for x64Copyright (C) Microsoft Corporation.  All rights reserved.main.cMicrosoft (R) Incremental Linker Version 14.11.25547.0Copyright (C) Microsoft Corporation.  All rights reserved./out:hello.exemain.objhello.lib

Run it:

E:\develop\so\xstatlib>helloHello world