I am running Linux Ubuntu 10.04 and I have a Windows 7 machine and a MacBook running Mac OS X 10.6.4. How can I write a simple C program (as in NOT QT!) like:
#include <stdio.h>
int main(int argc, char **argv)
{
printf("Hello Linux and Mac and Windows!")
return 0;
}
to run on all my machines without having to compile this program on Ubuntu, then Windows 7, then Mac OS X? Could I just create this in Ubuntu and cross compile it to run on several different operating systems?
UPDATE
I do not mean to produce ONE binary to run on all. I mean to produce THREE binaries from the same C code in the same OS.
The language C itself is cross-platform, because you don't directly run C code on machines. The C source code is compiled to assembly, and assembly is the platform specific code. The only non cross-platform part are the compilers and the resulting assembly.
C is a portable programming languageIf you write a C code in your machine, it will run on any machine which supports C, without modifying a single line of code. Because it is not tied to any hardware or system. We can say, it is a hardware independent language or platform independent language.
Linking C and C++ codeWhile C and C++ maintain a large degree of source compatibility, the object files their respective compilers produce can have important differences that manifest themselves when intermixing C and C++ code. Notably: C compilers do not name mangle symbols in the way that C++ compilers do.
C++ is cross-platform. You can use it to build applications that will run on many different operating systems. What is not cross-platform is the compilers that translate C++ into object code.
An executable has a specific format (e.g. ELF) and architecture (e.g. x86). Thus, you do have to compile multiple times. However, it is possible to cross-compile to e.g. Windows 7 x86 and Mac OS X x86 from Ubuntu. The procedures for each are different, as you would expect.
For Windows, you will want mingw32. See Compile Windows C console applications in Linux .
For OS X, see How to compile Intel Mac binaries on Linux? , which links to a tutorial.
You can search to find more information on each.
Unfortunately, the executable file formats used by Linux, Windows, and OSX are profoundly different in detail. There is no way to produce a single binary that works on all three.
It is possible to generate Windows and OSX executables using cross compilers from Linux (or vice versa in any other combination you like) but setting up the build environment is probably more trouble than it's worth. See http://www.kegel.com/crosstool/ if you really want to try that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With