-1

我正在尝试编译一些非常简单的 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;
}

而且我确实下载了最新的开发工具。如果有人可以提供帮助,那就太好了。

4

3 回答 3

3

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

于 2013-02-23T00:39:23.510 回答
3

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

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

于 2013-02-23T00:40:20.203 回答
3

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

于 2013-02-23T00:42:16.677 回答