9

I was trying my hands to compile on Ubuntu. So I typed a this much small program :

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

And this thing giving lots of errors:

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

I can do this easily in "C" . But what's my mistake in "C++" ?

4

2 回答 2

21

Use g++ instead of gcc to build your C++ program.

While gcc knows how to compile C++, by default it does not link against the C++ libraries that are required by your program.

From the manual:

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
       即使您以与 for 相同的方式调用编译器,它们也作为 C++ 程序
       编译 C 程序(通常使用名称 gcc)。

       但是,使用 gcc 并没有添加 C++ 库。g++ 是一个程序
       调用 GCC 并将 .c、.h 和 .i 文件视为 C++ 源文件而不是 C
       源文件,除非使用 -x,并自动指定链接到
       C++ 库。该程序在预编译 C 头文件时也很有用
       带有 .h 扩展名,用于 C++ 编译。在许多系统上,g++ 也是
       以名称 c++ 安装。
于 2013-03-30T10:17:26.373 回答
8

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

于 2013-03-30T10:17:57.407 回答