How does std::cout know where to print?

Viewed 696

Why does a terminal window open when I run my C++ program, and how does std::cout know that it's supposed to print to that terminal?

2 Answers

Every operating system has what is called a "standard output stream", when you use cout, c++ just tells the operating system to print to the stream. The operating system is what figures out where to output it.

The compiler recognises that you're writing a console based application and provides a runtime environment suited to the type of program you're writing.

The type of application is usually selected when you start a new project but in older compilers, the console type was the only type that was available. MS-DOS and CP/M provided terminal services, upon which the command line interpreter like "command.com" would be the default program that could call other programs like "myCppApp.exe".

The terminal services included an input stream (what you typed at the keyboard) and an output stream (what was displayed on the screen). These were treated as special files which were readonly (cin) and writeonly (cout).

C/C++ provided access to these standard disk operating system services by way of cin/cout.

When windows came along, rather than use the text console (which you can still see on some computers when they boot up or in BIOS settings) people preferred to use virtual console windows that emulated the text console within a graphical user interface.

So its kind of a combination of the operating system providing a pretend environment and the compiler providing a runtime code based on the fact your building a console application.

Related