6

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";
}
neatnick
  • 1,489
  • 1
  • 18
  • 29
Joey Franklin
  • 6,423
  • 7
  • 25
  • 22

5 Answers5

21

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
Matthew Lock
  • 13,144
  • 12
  • 92
  • 130
mmtauqir
  • 8,499
  • 9
  • 34
  • 42
  • Thanks...what's the difference? – Joey Franklin Jan 31 '12 at 22:23
  • 2
    gcc is a C compiler, g++ is a C++ compiler – AJG85 Jan 31 '12 at 22:24
  • g++ is probably just an alias for gcc...you can actually use gcc to compile c++ i think by using the `-x c++` command-line option... – mmtauqir Jan 31 '12 at 22:25
  • 1
    Technically gcc is the frontend for several compilers and linker tools but to ensure you get the right arguments you might as well use the right alias ... oh and it's `-lstdc++` to link with gcc. – AJG85 Jan 31 '12 at 22:28
  • 7
    `g++` will pull in the C++ library automatically. See http://stackoverflow.com/a/5854712/12711 for too much detail. – Michael Burr Jan 31 '12 at 22:32
3

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.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
1

Compile with g++ instead of gcc.

kichik
  • 33,220
  • 7
  • 94
  • 114
0

Try using g++ to compile your C++ code, instead of gcc, which is used for compiling C programs.

Alex Reynolds
  • 95,983
  • 54
  • 240
  • 345
0

Or you could still use gcc but explicitly link with the c++ library thusly:

gcc -o HelloWorldCompiled HelloWorld.cc -lstdc++
emsr
  • 15,539
  • 6
  • 49
  • 62