0

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?

1
  • 1
    Object files and static libraries have file formats too, as much as executables. Then you have ABI issues. Commented Mar 25, 2019 at 19:28

2 Answers 2

1

Compiling a C code turns it into a native binary/ native image. It is specific to the processor/OS on which it is compiled (unless of course you are not using a cross compiler). The binary/object will not run on another OS.

Only in case of languages like java, C# it is possible that you can compile for one OS and run on other (without rebuilding). This is because these languages create a managed binary/object. This managed object doesn't run directly on the OS. It runs on the virtual machine (JVM for Java and CLR for C#).

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments