How to write portable code in c++?

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

    OS-independent code is surprisingly hard to do in C++. Consider this trivial example:

    #include 
    int main(int argc, char** argv) {
      std::cout << argv[0] << std::endl;
    }
    

    That is perfectly valid C++, still it's nonportable because it won't accept Unicode command line arguments on Windows. The correct version for Windows would be:

    #include 
    int wmain(int argc, wchar_t** argv) {
      std::wcout << argv[0] << std::endl;
    }
    

    Of course that is again nonportable, working only on Windows and being nonstandard. So in fact you cannot even write a portable main() function in C++ without resorting to conditional compilation.

提交回复
热议问题