The “std::cout” is an inbuilt function of c++ that is used to print out variables or strings, for example, a simple “Hello World” statement. The error “undefined reference to std cout” can occur when trying to either write or execute a c++ program.
In this article, we will demonstrate the reasons for the error “undefined reference to std cout” and will provide the possible solutions to these reasons.
Reason 1: Missing Header File
The first reason involves the syntax of the code. The error can occur when we miss the header files that are supposed to be added before the program is written inside the main function. The following image shows a c++ code without any header keywords:
Solution: Add the Header File
The first way is to ensure that we have used the correct header keywords at the start of the code. The following codes need to be added:
#include <iostream> using namespace std;
For a better understanding, we are adding these files into our “sample.cpp” file. After doing so, execute the “sample.cpp” file:
Adding these header files will remove the error and allow the c++ file to compile and execute successfully, as demonstrated in the snippet below:
Reason 2: Use of Incorrect Compiler
This error can also occur while compiling the program to run it. GCC is the most standard compiler that is used for compiling programs in various languages such as c++. But the GCC keyword is used to compile the cpp file, which can often lead to problems since the standard C++ library contains “cout”. The following shows the error caused when using “gcc”:
Solution: Use g++ as a Compiler
To compile the code efficiently without any errors, we can use the “g++” keyword instead of the “gcc” keyword. This way, we do not have to explicitly link the “-lstdc++” standard library we mentioned above.
For instance, to compile the example.cpp, the following command is executed:
The snippet below shows how the program is compiled using g++ and then executed:
The error “undefined reference to std cout” occurs due to missing header keywords or due to issues with the gcc compiler. The first reason can be solved by simply adding the correct header keywords into the code, while the second reason for occurrence can be solved using the g++ command instead of gcc to compile the program. You have learned about the reasons for the error “undefined reference to std out” and their solutions are also described in detail.
TUTORIALS ON LINUX, PROGRAMMING & TECHNOLOGY