未定义的引用'std :: cout'

这应该是一个例子:

#include <iostream> using namespace std; int main() { cout << "Hola, moondo.\n"; } 

它引发错误:

 gcc -c main.cpp gcc -o edit main.o main.o: In function `main': main.cpp:(.text+0xa): undefined reference to `std::cout' main.cpp:(.text+0xf): undefined reference to `std::basic_ostream<char,std::char_traits<char> >& std::operator<< <std::char_traits<char>>(std::basic_ostream<char, std::char_traits<char> >&, char const*)' main.o: In function `__static_initialization_and_destruction_0(int,int)': main.cpp:(.text+0x3d): undefined reference to `std::ios_base::Init::Init()' main.cpp:(.text+0x4c): undefined reference to `std::ios_base::Init::~Init()' collect2: error: ld returned 1 exit status make: *** [qs] Error 1 

另外,这个例子:

 #include <iostream> int main() { std::cout<<"Hola, moondo.\n"; } 

抛出错误:

 gcc -c main.cpp gcc -o edit main.o main.o: In function `main': main.cpp:(.text+0xa): undefined reference to `std::cout' main.cpp:(.text+0xf): undefined reference to `std::basic_ostream<char,std::char_traits<char> >& std::operator<<<std::char_traits<char>>(std::basic_ostream<char,std::char_traits<char> >&, char const*)' main.o: In function `__static_initialization_and_destruction_0(int,int)': main.cpp:(.text+0x3d): undefined reference to `std::ios_base::Init::Init()' main.cpp:(.text+0x4c): undefined reference to `std::ios_base::Init::~Init()' collect2: error: ld returned 1 exit status make: *** [qs] Error 1 

注意:我正在使用Debian Wheezy。

编译程序:

 g++ -Wall -Wextra -Werror -c main.cpp -o main.o ^^^^^^^^^^^^^^^^^^^^ <- For listing all warnings when your code is compiled. 

因为cout存在于C ++标准库中,当使用gcc时,需要使用-lstdc++ 显式链接 ; g++默认链接标准库。

有了gcc ,( g++应该优于gcc

 gcc main.cpp -lstdc++ -o main.o 

是的,使用g++命令为我工作:

 g++ my_source_code.cpp