繁体   English   中英

简单的C ++矢量程序无法编译

[英]Simple c++ vector program not compiling

我刚刚开始学习c ++并编写了这个非常简单的程序来使用向量。 但是它不能编译。 我想查看下标不存在元素的行为。

#include <iostream>
#include <string>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;

int main() {
    vector<int> list;
    cout << list[0];
    return 0;
}

当我使用cc main.cpp在Mac上编译它时,出现了一个无法理解的错误。

Undefined symbols for architecture x86_64:
  "std::__1::basic_ostream<char, std::__1::char_traits<char> >::operator<<(int)", referenced from:
      _main in main-651b3f.o
  "std::__1::cout", referenced from:
      _main in main-651b3f.o
  "std::terminate()", referenced from:
      ___clang_call_terminate in main-651b3f.o
  "operator delete(void*)", referenced from:
      std::__1::__vector_base<int, std::__1::allocator<int> >::~__vector_base() in main-651b3f.o
  "___cxa_begin_catch", referenced from:
      ___clang_call_terminate in main-651b3f.o
  "___gxx_personality_v0", referenced from:
      _main in main-651b3f.o
      Dwarf Exception Unwind Info (__eh_frame) in main-651b3f.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

cLion IDE不会抱怨同一程序的编译问题。 有什么想法吗?

cc是用于生成C程序的命令。 改为编写c++

这些通常分别是gccg++clangclang++等可执行文件的别名。

即使这些可执行文件最终调用相同的前端(通常是正确的),您调用哪个命令也很重要。 例如, cc别名不会导致链接C ++标准库,这正是您所遇到的问题。

顺便说一句,由于您试图输出不存在的元素,因此程序具有未定义的行为。 因此,从技术上讲 ,您甚至可以在修复build命令后获得此结果;)

您正在尝试使用C编译器编译C ++代码。 您应该使用适当的C ++编译器(例如c++ )。

另一件事是程序中存在未定义的行为:

vector<int> list;
cout << list[0];

向量总是被初始化为空。 因此,您尝试访问尚不存在的元素。 这很可能导致段错误。 尝试插入一些东西:

vector<int> list;
list.push_back(1);
cout << list[0];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM