链接C ++程序时出错

时间:2013-02-23 00:36:59

标签: c++ gcc compilation compiler-errors

我正在尝试编译一些非常简单的C ++代码,每次尝试时我都会收到此错误:

Undefined symbols for architecture x86_64:
"std::basic_ostream<char, std::char_traits<char> >::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))", referenced from:
  _main in ccdb9vrE.o
"std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string()", referenced from:
  _main in ccdb9vrE.o
"std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()", referenced from:
  _main in ccdb9vrE.o
"std::ios_base::Init::Init()", referenced from:
  __static_initialization_and_destruction_0(int, int)in ccdb9vrE.o
"std::ios_base::Init::~Init()", referenced from:
  ___tcf_0 in ccdb9vrE.o
"std::cin", referenced from:
  _main in ccdb9vrE.o
"std::cout", referenced from:
  _main in ccdb9vrE.o
"std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)", referenced from:
  _main in ccdb9vrE.o
"std::terminate()", referenced from:
  _main in ccdb9vrE.o
"std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)", referenced from:
  _main in ccdb9vrE.o
"std::basic_ostream<char, std::char_traits<char> >& std::operator<< <char, std::char_traits<char>, std::allocator<char> >(std::basic_ostream<char, std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)", referenced from:
  _main in ccdb9vrE.o
"std::basic_istream<char, std::char_traits<char> >& std::operator>><char, std::char_traits<char>, std::allocator<char> >(std::basic_istream<char, std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)", referenced from:
  _main in ccdb9vrE.o
"___gxx_personality_v0", referenced from:
  Dwarf Exception Unwind Info (__eh_frame) in ccdb9vrE.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status

我正在使用此命令编译它:

$ gcc script.cc

这是脚本的代码:

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

int main() {
        cout << "Please enter your name:\n";
    string name;
    cin >> name;
    cout << "Hello, " << name << endl;

    return 0;
}

我确实已经下载了最新的开发工具。如果有人能提供帮助那就太棒了。

3 个答案:

答案 0 :(得分:3)

使用g ++,因为它的c ++文件不是c文件... 它应该这样工作......

答案 1 :(得分:3)

gcc是GNU C 编译器可执行文件的名称;因此,它意味着编译和构建C代码。 要将代码编译为C ++,请使用g++可执行文件。

gcc实际上会编译C ++代码(基于文件扩展名),但不会正确链接生成的二进制文件(由于省略了libstdc++)。

答案 2 :(得分:3)

无论如何:到目前为止,没有一个答案提到了为什么链接不能与GCC一起使用的实际原因,而是使用G ++。问题不在于编译步骤,而在于链接。 gcc默认情况下不会链接到C ++标准库,g++会这样做。