How to write portable code in c++?

后端 未结 12 2012
情话喂你
情话喂你 2020-11-30 03:47

What are the things that I should keep in mind to write portable code? Since I\'m a c++ beginner, I want to practice it since beginning.

Thanks.

12条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 04:41

    Some guidelines:

    1. Keep the business end of the code and the GUI separate.
    2. Avoid the use of compiler specific crutches (#pragma, etc.)
    3. Use conventional expressions that won't change behavior with compiler/platform instead of cute bit manipulation tricks.
    4. If it touches hardware it belongs in a device driver.
    5. Use data type headers like types.h (uint32_t, etc.).
    6. Use an operating system abstraction layer so you are not calling operating system calls directly.

    Sometimes you have to trade off efficiency and performance to gain portability. For example, if your code requires accessing fields out of a buffer you can always cast a packed struct to the buffer pointer. But that is horribly non-portable. So instead you need to use named pointers calculated with offsets -- sometimes with boundary alignment handling code. Not pretty, but portable. Fortunately you can hide a lot of that stuff with judicious use of class interfaces.

    Not all code needs to be written that way. If you design your application in a very modular way with well defined boundaries of responsibility then 90-95% of the code can be portable without pain. Then just isolate the 5-10% in a very localized area that would need to be customized for a new platform.

提交回复
热议问题