1

I have a simple bit of code which is having trouble compiling.

#include <iostream>
#include <string>
using namespace std;

int main(int argc, char **argv) {
  string hello = "Hello World";
  printf("%s\n",hello.c_str());
  return 0;
}

compiling with "gcc test.cpp -o test" returns the following message.

/tmp/ccgbRaOf.o: In function main': test.cpp:(.text+0x27): undefined reference tostd::allocator::allocator()' test.cpp:(.text+0x3e): undefined reference to std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&)' test.cpp:(.text+0x4a): undefined reference tostd::allocator::~allocator()' test.cpp:(.text+0x56): undefined reference to std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::c_str() const' test.cpp:(.text+0x6a): undefined reference tostd::__cxx11::basic_string, std::allocator >::~basic_string()' test.cpp:(.text+0x8f): undefined reference to std::allocator<char>::~allocator()' test.cpp:(.text+0xa9): undefined reference tostd::__cxx11::basic_string, std::allocator >::~basic_string()' /tmp/ccgbRaOf.o: In function __static_initialization_and_destruction_0(int, int)': test.cpp:(.text+0xe9): undefined reference tostd::ios_base::Init::Init()' test.cpp:(.text+0xfe): undefined reference to std::ios_base::Init::~Init()' /tmp/ccgbRaOf.o:(.data.rel.local.DW.ref.__gxx_personality_v0[DW.ref.__gxx_personality_v0]+0x0): undefined reference to__gxx_personality_v0' collect2: error: ld returned 1 exit status

What am I doing wrong?

Mat
  • 202,337
  • 40
  • 393
  • 406
Henry B
  • 29
  • 3
  • https://stackoverflow.com/questions/172587/what-is-the-difference-between-g-and-gcc – Mat Feb 26 '20 at 18:36

2 Answers2

1

You compile it with gcc which is for C, but your code is C++. Use g++.

Eraklon
  • 4,206
  • 2
  • 13
  • 29
1

It does not work because you are using a C compiler. For C++ you need a different compiler. Try with g++

Gerhard Stein
  • 1,543
  • 13
  • 25