g ++编译错误

kio*_*kio 8 c++ ubuntu g++

我是Ubuntu的新手.我试着编译一个简单的"Hello World!" Ubuntu 11.04中的c ++代码,带有该代码(在终端中):

gcc -Wall -W -Werror tex.cpp -o tex. 
Run Code Online (Sandbox Code Playgroud)

但编译器返回了很多错误:

/tmp/ccL8c1p8.o: In function `main':
tex.cpp:(.text+0xa): undefined reference to `std::cout'
tex.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*)'
/tmp/ccL8c1p8.o: In function `__static_initialization_and_destruction_0(int, int)':
tex.cpp:(.text+0x3d): undefined reference to `std::ios_base::Init::Init()'
tex.cpp:(.text+0x42): undefined reference to `std::ios_base::Init::~Init()'
collect2: ld returned 1 exit status
mohrd@mio:~$ gcc -Wall -W -Werror tex.cpp -o tex.
/tmp/ccEke5JP.o: In function `main':
tex.cpp:(.text+0xa): undefined reference to `std::cout'
tex.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*)'
/tmp/ccEke5JP.o: In function `__static_initialization_and_destruction_0(int, int)':
tex.cpp:(.text+0x3d): undefined reference to `std::ios_base::Init::Init()'
tex.cpp:(.text+0x42): undefined reference to `std::ios_base::Init::~Init()'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

简单代码:

#include <algorithm>
#include <iostream>
using namespace std;

int main ()
{
  std::cout << "Hello World!";
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么?我该怎么办?

非常感谢 ...

jco*_*der 32

您需要使用g ++(或c ++)命令来编译您的程序,使用"gcc"将其编译为c ++,因为.cpp扩展名但不是必需的c ++库中的链接.

  • 或者在命令行中添加`-lddc ++`以链接标准C++库.但用"g ++"编译是更好的解决方案. (5认同)

Amo*_*son 5

使用g ++而不是gcc来编译C++代码:

g++ -Wall -W -Werror tex.cpp -o tex
Run Code Online (Sandbox Code Playgroud)

默认情况下,gcc不会链接stdc ++库,这是代码所必需的.