Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I compile HelloWorld in C++?

I'm trying to compile a simple Hello World program in C++ but I keep getting the following error...why?

gcc -o HelloWorldCompiled HelloWorld.cc
/tmp/ccvLW1ei.o: In function `main':
HelloWorld.cc:(.text+0xa): undefined reference to `std::cout'
HelloWorld.cc:(.text+0xf): 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*)'
/tmp/ccvLW1ei.o: In function `__static_initialization_and_destruction_0(int, int)':
HelloWorld.cc:(.text+0x3d): undefined reference to `std::ios_base::Init::Init()'
HelloWorld.cc:(.text+0x42): undefined reference to `std::ios_base::Init::~Init()'
/tmp/ccvLW1ei.o:(.eh_frame+0x12): undefined reference to `__gxx_personality_v0'
collect2: ld returned 1 exit status

Here is my program:

#include <iostream>
using namespace std;

int main()
{
  cout << "Hello World\n";
}
like image 267
Joey Franklin Avatar asked Jan 31 '12 22:01

Joey Franklin


People also ask

Why my Hello World program is not working?

It's only fitting that the first thing it says is "Hello, world!" There can be syntax error in your program like missing header file, termination syntax error etc. So catch these errors and remove them. Then your program will work.

Does GCC work with C?

GCC is an integrated distribution of compilers for several major programming languages. These languages currently include C, C++, Objective-C, Objective-C++, Fortran, Ada, D, and Go. The abbreviation GCC has multiple meanings in common use.

Can you use g ++ to compile C?

gcc is used to compile C program. g++ can compile any . c or . cpp files but they will be treated as C++ files only.


2 Answers

Use g++ not gcc. gcc is a C compiler, whereas g++ is a C++ compiler.

g++ -o hwcompiled helloworld.cc

Then to execute your compiled program:

./hwcompiled
like image 76
mmtauqir Avatar answered Sep 28 '22 06:09

mmtauqir


You have to use g++, not gcc. It seems that gcc understands that it's C++ (so it doesn't give syntax errors), but "forgets" to link it to the C++ standard library.

like image 21
Matteo Italia Avatar answered Sep 28 '22 07:09

Matteo Italia