c++ - 简单的 C++ vector 程序未编译

标签 c++ c++11 vector

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

#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;
}

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

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++ 标准库,这正是您遇到的问题。

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

关于c++ - 简单的 C++ vector 程序未编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43957323/

相关文章:

c++ - 将 shared_ptr 作为指向指针的指针传递

c++ - 为什么嵌套的initializer_list会导致内存泄漏

c++11 move 不生效?

c++ - std::istream_iterator 停止前进

c++ - 日期格式操作(YYYY/MM/DD-to-MM/DD/YYYY)

c++ - 在添加元素时使 vector 更高效

c++ - 外部库错误 C++

c++ - 从 sqlite3 数据库(.db 文件)检索数据并将其存储在 C++ 中的简单字符串中

c++ - 将字符串分解为单独的元素

c++ - 检查两个 vector<T> 之间的差异