Pure C code + C compiler = cross platform code?
If I have a code, fully written in C, using only libraries written also in C, and I have a compiler, like GCC, supporting many platforms, can I be sure that this code will run for any architecture supported by compiler? For example, can I take Flex or CPython , compile and use it, let say, at AVR?
Edit:
- compile and run, of cou开发者_运维技巧rse
- no GUI
No, it's hard to say without seeing your code. For example, if you depend on that long is 4 bytes, it won't be right on 64bit machine.
"fully written in C" doesn't guarantee in any way that the code is portable. A portable compiler like GCC abstracts away the CPU architecture details, but the moment you use a system call specific to a particular OS, your code becomes unportable unless you surround the fragment in an #ifdef WHATEVER_OS
. This is why standards like POSIX have emerged to unify the system call interface across different operating systems.
Limiting your code to the POSIX-defined system calls and using a POSIX-compliant operating system should generally stop you from worrying, with little exceptions.
source code portability and compilability should be granted in your scenario.
things might change if you would use external libraries or GUI frameworks which depend on the specific OS but this is not your case you you should be good to go.
The response is "they'll probably compile but there is a possibility they won't run". The problem is the resources available to you. Let's say you program for your 2gb machine. Will your program run on a 256mb machine? Could a DOS machine run CPython? But they'll probably compile :-) (technically you could have a program (the code) too much big to fit in the address space of the target machine. If your .exe/.out is 18mb and the target machine has an address space of 16mb, you can't even compile)
Simply using C doesn't guarantee that the code is portable to any platform that supports C. There's a boat-load of traps to step into, like dependence on type-sizes, endianess or undefined behavior.
In reality, a non-trivial program is rarely portable to much except the platforms you have actually verified that it runs on. But you can certainly take measures to try and decrease the chance of problems, though.
精彩评论