星期日, 9月 11, 2011

[c++] gcc? g++?

前幾天試著在mac 終端幾底下,用gcc compile一個簡單的hello world程式:

#include <iostream>
using namespace std;
int main(){
        cout << "Hello World!";
        return 0;
}



$ gcc test.cpp

但是一直會出現錯誤:

Undefined symbols:
  "___gxx_personality_v0", referenced from:
      ___gxx_personality_v0$non_lazy_ptr in cchU1h80.o
  "std::ios_base::Init::~Init()", referenced from:
      ___tcf_0 in cchU1h80.o
  "std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)", referenced from:
      _main in cchU1h80.o
  "std::ios_base::Init::Init()", referenced from:
      __static_initialization_and_destruction_0(int, int)in cchU1h80.o
  "std::cout", referenced from:
      __ZSt4cout$non_lazy_ptr in cchU1h80.o
ld: symbol(s) not found
collect2: ld returned 1 exit status


好像是找不到函式庫的樣子,但是當時沒多想就放棄了,今天突然想到用改成g++試試:
$ g++ test.cpp

然後就成功了!

上網查了一下,才知道gcc在compile的時候,不會link到c++的standard library
所以會有錯誤。

如果要用gcc compile的話,只要加上 "-lstdc++"就可以囉!像是:
$ gcc -lstdc++ test.cpp

---
*gcc 是GNU Compiler Collection,裡面包含很多語言的compiler
*g++是c++的一個compiler,有包含在gcc中

沒有留言:

張貼留言