g++编译错误

9

我是Ubuntu的新手。 我尝试在Ubuntu 11.04上编译一个简单的C++代码“Hello World!”,使用以下代码(在终端中):

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;
}

为什么?我该怎么办?非常感谢...

3
你使用gcc来编译C++程序吗?使用g++。 - netcoder
你在标题中说的是g++,但在正文中使用的是gcc - 那么到底是哪个? - user195488
我是新手,真的不知道gcc和g++之间的区别! - kio
5个回答

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

5
要连接标准的C++库,请在命令行中添加“-lstdc ++”。但是,使用“g ++”编译是更好的解决方案。 - Adam Rosenfield

6

在编译C++代码时,请使用g++而不是gcc:

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

gcc默认不连接stdc++库,而这个库对于您的代码来说是必须的。


4

请使用g++命令代替gcc


1

尝试:

g++ -Wall hello.cpp -o hello

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

-Wall表示警告所有,因此您已经可以看到所有警告。

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

注:当然,-Werror仍然是您的选择。

注2:您的代码中不需要#include <algorithm>,因此可以将其删除!


-1

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接