无法编译C ++程序

时间:2013-03-30 10:15:40

标签: c++ ubuntu

我正在尝试在Ubuntu上编译。 所以我输入了一个非常小的程序:

#include <iostream>
using namespace std;
int main(){
int cases;
cin>>cases;
return 0;
}

这件事给出了很多错误:

umair@ubuntu:~/cpp$ gcc -Wall -W -Werror 2.cpp -o 1
/tmp/ccU4nAIg.o: In function `main':
2.cpp:(.text+0x10): undefined reference to `std::cin'
2.cpp:(.text+0x15): undefined reference to `std::istream::operator>>(int&)'
/tmp/ccU4nAIg.o: In function `__static_initialization_and_destruction_0(int, int)':
2.cpp:(.text+0x4d): undefined reference to `std::ios_base::Init::Init()'
2.cpp:(.text+0x5c): undefined reference to `std::ios_base::Init::~Init()'
/tmp/ccU4nAIg.o:(.eh_frame+0x13): undefined reference to `__gxx_personality_v0'
collect2: error: ld returned 1 exit status

我可以轻松地在&#34; C&#34; 。但是我在&#34; C ++&#34;中的错误是什么? ?

2 个答案:

答案 0 :(得分:21)

使用g++代替gcc来构建您的C ++程序。

虽然gcc知道如何编译 C ++,但默认情况下它不会链接与程序所需的C ++库。

从手册:

Compiling C++ Programs

       C++ source files conventionally use one of the suffixes .C, .cc, .cpp, .CPP,
       .c++, .cp, or .cxx; C++ header files often use .hh or .H; and preprocessed C++
       files use the suffix .ii.  GCC recognizes files with these names and compiles
       them as C++ programs even if you call the compiler the same way as for
       compiling C programs (usually with the name gcc).

       However, the use of gcc does not add the C++ library.  g++ is a program that
       calls GCC and treats .c, .h and .i files as C++ source files instead of C
       source files unless -x is used, and automatically specifies linking against the
       C++ library.  This program is also useful when precompiling a C header file
       with a .h extension for use in C++ compilations.  On many systems, g++ is also
       installed with the name c++.

答案 1 :(得分:8)

要编译C ++,请调用g++而不是gcc