Search code examples
compilationlinkeroperating-systemabiobject-files

Can static libraries that don't rely upon the C standard library be compiled on one OS, then moved to another?


I know that for full programs this is impossible because of executable file formats and syscalls, however if you had a file with:


    int add(int a, int b) {
        return a + b;
    }

Could you compile it as an object file or static library on Linux, and then use it on macOS or Windows?


Solution

  • Can static libraries that don't rely upon the C standard library be compiled on one OS, then moved to another?

    In theory; yes. Note that a compiler is just something that converts a primary language (e.g. C) into a secondary language (e.g. maybe native code for a specific OS and specific CPU; but maybe also BASIC source code or web-assembly source code or some kind of portable byte-code or anything else).

    The only thing that really matters is that whatever uses the secondary language understands the secondary language.

    In practice; for static libraries the secondary language includes things like object file formats and calling conventions; and "whatever uses the secondary language understands the secondary language" includes understanding the object file format, understanding the calling conventions, etc. Typically compilers are configured such that their secondary language matches whatever makes sense for the computer the compiler is running on, and because of this often you can't compile a static library on one computer and move it to another computer (with a different compiler and/or OS and/or CPU).

    However, "typical" does not indicate a necessity. Cross-compilers are entirely possible.

    For an example, you can port GCC (and it's tools - linker, etc) to Windows and use your cross-compiler to create static libraries that can be used by compiler's designed for (and running on) Linux; and if you do this you probably won't be able to use the cross compiler (running on Windows) to create static libraries for other compilers that are also running on Windows.