Reputation: 6998
I'm just starting to learn c++ and wrote this very simple program to use vectors. But it doesn't compile. I want to see the behavior of subscripting a non-existent element.
#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;
}
when I compile it on my mac using cc main.cpp
, I get an incomprehensible error.
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 doesn't complain about compilation issues for the same program. Any ideas what's happening?
Upvotes: 1
Views: 1604
Reputation: 385295
cc
is a command to build C programs. Write c++
instead.
These are typically aliases to executables like gcc
and g++
(respectively), or clang
and clang++
(respectively).
Even if these executables ultimately invoke the same front-end (which is usually true), it matters which command you invoke. For example, the cc
alias will not result in the C++ standard library being linked in, which is precisely the problem you're seeing.
By the way, your program has undefined behaviour since you're trying to output an element that doesn't exist. So, technically, you could even get this result after fixing the build command ;)
Upvotes: 7
Reputation: 56547
You are trying to compile a C++ code with C compiler. You should use a proper C++ compiler (e.g. c++
) instead.
The other thing is that there's an undefined behaviour in your program:
vector<int> list;
cout << list[0];
Vectors are always initialized as empty. So you try to access an element that doesn't exist yet. This will most likely result in a segfault. Try inserting something:
vector<int> list;
list.push_back(1);
cout << list[0];
Upvotes: 4