g ++编译错误

时间:2011-07-27 15:34:15

标签: c++ ubuntu g++

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

gcc -Wall -W -Werror tex.cpp -o tex. 

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

/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

简单代码:

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

int main ()
{
  std::cout << "Hello World!";
  return 0;
}

为什么呢?我该怎么办???

非常感谢...

5 个答案:

答案 0 :(得分:32)

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

答案 1 :(得分:5)

使用g ++代替gcc编译C ++代码:

g++ -Wall -W -Werror tex.cpp -o tex

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

答案 2 :(得分:4)

使用g++命令代替gcc

答案 3 :(得分:1)

尝试:

g++ -Wall hello.cpp -o hello

因为您正在尝试编译C++代码,而不是C代码!

-Wall表示Warning ALL,因此您已经看到了所有警告

另外,有意义地命名您的程序和源文件!

LE:当然-Werror仍然是您的选择

LE2:您的代码中不需要#include <algorithm>,因此您可以删除它!

答案 4 :(得分:-1)

我在创建一个巨大的数组 (50005) 项时遇到了同样的错误。小心

相关问题