C Program Portability
As we know java is a platform independent language due to JVM it's program can run at any OS. What about C/C++? could C/C++ exe run at any OS ? Could we have done something about this(Like write once run anywhere)? please clear my doubt about this. 开发者_Python百科Thanks
No - an executable is built for a specific operating system and hardware (CPU) architecture.
If you are carefull not to use any OS specific functions, or any assumptions about word size etc, then c++ source can be recompiled to run anywhere.
C and C++ are traditionally transformed into machine code for a particular CPU type/family, and packed within a format that a particular operating system can start.
There's nothing stopping anyone from making a C or C++ compiler that compiles code to run on a virtual machine in the same sense that java source code is compiled to byte code intended to run on the jvm. Someone
(The usefulness of doing so is another matter though, and e.g. while it's quite far from standard C++, C++/.CLI compiles a C++ like language to run on .NET)
Theorically, C programs only need a compiler that produce executable binaries for the target platform. That's why C is used in almost any embedded platform.
Practically, that require a separate compilation for each target platform.
C++ is another beast, clearly more complex and rich of features. Depending on the platform, you might or not have a compiler for C++, and if you have, embedded platform often require (for often non-obvious and sometimes critiquables reasons) that some C++ features are deactivated.
So with C++ you still "can" compile for any target platform, because it is a system programming language, like C (meaning that you're "close to the metal" with those languages).
However, there are still some problems you have to solve if you want to target some platforms :
- some platform constructors will not allow you to run binaries on their platforms, only to sue their "secured" virtual-machine based language (whatever it is);
- some platform constructors will provide compilers for their platforms, but with limited features, making them too poor to use for industrial developpement;
So theorically, C and C++ can run anywhere, if you compile for the target and that you use only cross-platform code/library. In practice, it depends on the context.
Executable programs are platform and OS dependent. There are emulators in some OS that allows to run executables of other platforms (such as wine, dosbox etc. and of course VMWare) but this is an emulation/virtualization only.
Each operating system has it's own executable format, so you have to compile your C(++) program separately for each OS. If you use cross platform libraries, you can easily recompile your program without having to change your code a lot.
精彩评论