skip to Main Content

If C++ is machine dependent, then how does software written in C++ work on different computers?
Photoshop is written in C++, yet it runs on many computers, but C++ is not cross platform.

2

Answers


  1. As James Adikson said an executable is compiled for each platform. But you may wonder what about handling platform specifics.

    For starters a Windows executable file is internally different than a Linux one (Using Windows and Linux as examples). That is handled by having different compilers or specifying different target platforms to the compiler.

    Then you have interaction with the OS, for example in Windows your file paths use ” as separator while in linux or unix they use ‘/’, these kind of things are usually handled by using #ifdef preprocessor directives with macros defined by the compiler. Something like:

    #ifdef __WINDOWS__
    char separator = '\';
    #else
    char separator = '/';
    #endif
    

    Notice that this is conditional compilation so it won’t define the same variable two times.

    Also, some things are made platform independent in the standard library. File interaction is different on each system but you can create a file and append to it in a platform-independent way using the standard library.

    std::ofstream file("my_file.txt");
    file << "Hello World!n";
    

    This will compile with a Linux C++ compiler or a Windows C++ compiler and the resulting executables will communicate with their respective host OSes appropriately.

    Login or Signup to reply.
  2. A few more examples of platform independency:

    • std::thread and related standard library classes
    • std time classes
    • ntohs/htons etc for endianness-independence
    • uint64_t, int32_t etc. for cases where you need to know variable size
    • ifdefs for OS-specific error codes from BSD socket API
    • and much more…
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search