Aravind .KEN Aravind .KEN - 2 months ago 6
Linux Question

Does all c++ code(exactly the same) will compile and work the same on Windows system as well as Linux Based system? and Why?[in c++] [RBIx]

Till now, i have been successfully compiling a same code in both windows and Linux Based system using code-blocks! And got no errors till now but i am just c++ beginner and my program are simple so i couldn't figure it !so i thought maybe I could get it cleared from you, guys!

Does all c++ code(exactly the same) will compile and work the same on Windows system as well as Linux Based system? and Why?



If your answer is:YES,they do


  • Why are same c++ programs in different versions (Windows version and
    Linux version)?



If your answer is:No,they dont


  • Why? and What code work in windows and not in Linux and vice versa?

  • Is there any c++ code to find whether it is running in windows based
    system or Linux based system?

  • Does all c++ code(exactly the same) will compile and work the same on
    MAC system as well as Linux Based system?



Thanks for reading

Answer

There are many requirements for C++ code that must be met, if you want it to compile on two different OS:

  • Does your code use OS-specific libraries? Good example is <windows.h>. Such code won't compile on any OS other than Windows
  • Does your compiler provide appropriate extensions on OS A to support OS B libraries?

The best way would be to avoid both of these situations. Another question is:

  • Does compiler on OS A use the same C++ standard version as compiler on OS B?

If you use features from C++14 with C++14-supporting compiler on OS A, but compiler on OS B does not support it, it simply won't compile.

Why are same c++ programs in different versions (Windows version and Linux version)?

Because C++ standard doesn't provide information about OS without some additional libraries or compiler extensions. There might be also some differences in string parsing that you use in your code, for example when opening files or writing to files.

Why? and What code work in windows and not in Linux and vice versa?

Why is that, see above. Only code that uses exacly the same C++ standard without any OS specific aspects will compile of different OS. You can hax this with conditionally compiled code,

see this.

Is there any c++ code to find whether it is running in windows based system or Linux based system?

Compilers should provide prefedined macros, so you can check what OS you are running.

Does all c++ code(exactly the same) will compile and work the same on MAC system as well as Linux Based system?

No, definitely not all, reason given above.

Comments