Open-Source Internship opportunity by OpenGenus for programmers. Apply now.
In this article, we have present the reason behind the error "Undefined reference to std::cout" and different approaches to fix this error.
Table of contents:
- Reason behind the error
- Fix 1: Compile with g++ or clang++
- Fix 2: Add header file
- Fix 3: For Microsoft's compiler MSVC
- Fix 4: Fix GCC/ G++/ Clang build
Reason behind the error
On compiling a C++ program, you may face this compilation error:
code.cpp:(.text+0x3d): undefined reference to 'std::cout'
This comes from the line:
std::cout << data << std::endl;
The reason is that the compiler is unable to find where the function cout has been defined. This is a standard C++ function.
Make sure you are working on a C++ code (not on a C code).
Fix 1: Compile with g++ or clang++
The most common problem is that you are trying to compile a C++ program with a C compiler such as gcc or clang. To compile a C++ program, we need a C++ compiler such as g++ or clang++.
If you need to use gcc, add this explicit flag -lstdc++ to include C++ standard libraries which are included automatically with g++.
gcc -lstdc++ code.c
If you are using gcc in a cmake file, use the following within cmake:
-DCMAKE_EXE_LINKER_FLAGS="-lstdc++"
The overall compilation command will be same. Just replace gcc with g++ or clang with clang++.
cout is a feature in C++ only.
g++ code.cpp
// OR
clang++ code.cpp
Fix 2: Add header file
Add this at the top of your C++ program if you missed:
#include <iostream>
using namespace std;
Compile your C++ program and the error should be fixed.
Fix 3: For Microsoft's compiler MSVC
If you are using MSVC, include the following header files:
#include "stdafx.h"
#include <iostream>
Note the order is important. This should fix the issue.
Fix 4: Fix GCC/ G++/ Clang build
If the other fixes have not worked, it is highly likely that your GCC compiler installation is broken.
The suggestion is to build GCC/G++ from source so that the compiler installation is successful and you can compile your C++ code.
With the fixes in this article at OpenGenus, this issue of "Undefined reference to std::cout" should be fixed now. Continue your development work.