What is meant when a piece of code is said to be portable? [closed]

时光怂恿深爱的人放手 提交于 2019-12-01 05:19:30

Portable code is code that is not tightly coupled to one specific platform, or which is coupled as loosely as possible to platform-specific APIs. It is "portable" in that the amount of work required to move it from one platform to another is low.

Portable code is desirable when you intend to write code meant to be used by a large audience, on a wide variety of platforms.

Portability is primarily a concern in compiled languages, as interpreted languages typically rely on an interpreter to provide a uniform interface at runtime. It is still quite possible to write overly platform-specific code in an interpreted language by relying on features like backticks or exec for executing commands in the local environments, rather than accessing the same features through a library which may have different platform-specific implementations.

Libraries are often very concerned with portability as their primary purpose is to provide a consistent API across platforms.

Writing portable code involves minimizing the number of places your code must "reach down" and touch the underlying operating system outside of standard APIs. Typically you would encapsulate such access so that there is a single place in your codebase which must be ported from platform to platform while the bulk remains unchanged.

What does portability mean?

It means coding a program in a way so that the same code works in different environments; for example different processors, different operating systems, different versions of libraries etc.

If your code is portable, you should be able to just re-compile it on any new system and it should run without problems.

Why is it important?

The reason it's so important is because non-portable code can cause many problems in regard to maintenance - managing multiple versions, poor readability/understandability of the code to name a few.

Portable code is easy to move to other platforms -- either other compilers or other operating systems, with a minimum of changes needed to facilitate the migration.

Ideally this is achieved by only making use of standards (types, functions, definitions that are defined in system-provided header files, where on another system those header files might be modified by the compiler / OS vendor to be correct for that system).

Sometimes use of standards is insufficient, requiring use of (generally ugly) #ifdef's sprinkled throughout the code.

My statements assume a C/C++ like language. Many other languages are more intrinsically portable.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!