How to write portable code in c++?

后端 未结 12 2010
情话喂你
情话喂你 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

    The unwary programmer is likely to walk into a whole lot of traps, that we can attempt to categorize. But let me tell you first: as an absolute it's impossible.

    The problem is that even standard-conforming code might not be portable because of a particular compiler issue.

    Now here are the main categories that I can think off the top of my head.

    Compiler extensions

    Like for example the use of variables arrays:

    void func(int const n)
    {
      int array[n];
    }
    

    This is not standard, but many compilers support it nonetheless because it's just practical.

    Standard libraries extensions

    Many standard libraries implementations provide a std::hash_map which never was specified. If you use it in your code, it's not portable.

    The modern trend is to stash this stuff into the std::tr1 namespace so that programmers are aware that this is an extension.

    Also be aware that many define typedef or macros that are not generic (for example PRETTY_FUNCTION). No macro is specified by the standard, and very few typedef are.

    Platform specific

    For example, the size and alignment of int or double is not specified in the standard. If you do bit-twiddling and expect it to have 32 bits, you'll be screwed on 64 bits platforms even without changing your compiler.

    Platform API

    Our programs are meant to be compiled, and they are often meant to interact with the computer they run on:

    • for access to the hardware
    • for access to the filesystem
    • for access to the screen

    You need to find cross-platform portable APIs, or roll your own. Check some libraries in the list below.

    Libraries

    Most well-written libraries are largely portable, just make sure that they support:

    • the compilers you are interested in
    • the platforms you are interested in

    Good libraries involve:

    • Apache (the collection of libraries)
    • Boost
    • Qt (for graphic)
    • ICU (for Unicode handling)

    The others you need to review... and that takes time.

    I don't think there is a perfect answer there. But since perfect portability is not possible you need to decide which compilers and platform you wish to support.

    For the platform, you should begin with Windows and one Linux flavor. For the compilers, pick any two (with Comeau if you can afford it).

提交回复
热议问题