我刚开始学习 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++
。
这些通常是可执行文件的别名,例如 gcc
和 g++
(分别),或 clang
和 clang++
(分别)。
即使这些可执行文件最终调用相同的前端(这通常是真的),调用哪个命令也很重要。例如,cc
别名不会导致链接到 C++ 标准库,这正是您遇到的问题。
顺便说一句,你的程序有未定义的行为,因为你试图输出一个不存在的元素。所以,技术上,您甚至可以在修复构建命令后获得此结果 ;)
关于c++ - 简单的 C++ vector 程序未编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43957323/