[英]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++
。
這些通常分別是gcc
和g++
或clang
和clang++
等可執行文件的別名。
即使這些可執行文件最終調用相同的前端(通常是正確的),您調用哪個命令也很重要。 例如, 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.