Compiling a C++ program with GCC

C++Server Side ProgrammingProgramming

Here we will see how to compile C++ program using GCC (GNU C Compiler). Let us consider, we want to compile this program.


using namespace std;
main() {
   cout << "Hello World. This is C++ program" << endl;

If this is a C program, we can compile with GCC like below −

gcc test.c

But if we put c++ filename in that area, it may generate some error.

gcc test.cpp


/tmp/ccf1KGDi.o: In function `main':
1325.test.cpp:(.text+0xe): undefined reference to `std::cout'
1325.test.cpp:(.text+0x13): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& 
std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
1325.test.cpp:(.text+0x1d): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, 
std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
1325.test.cpp:(.text+0x28): undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))'
/tmp/ccf1KGDi.o: In function `__static_initialization_and_destruction_0(int, int)':
1325.test.cpp:(.text+0x58): undefined reference to `std::ios_base::Init::Init()'
1325.test.cpp:(.text+0x6d): undefined reference to `std::ios_base::Init::~Init()'
collect2: error: ld returned 1 exit status

This is not compilation error. This is linking error. To add the correct linker, we have to use –lstdc++ option.

gcc test.cpp -lstdc++


$ ./a.out
Hello World. This is C++ program
Published on 08-May-2019 08:43:56