天天看點

gcc和g++的差別

 gcc和g++的差別

Author: Chaos Lee

Date: 2012/04/28

         首先,是名字上的差別(廢話?)。gcc開始時候的名字是gnu c compiler, 就是說設計的初衷是用來編譯C語言的。 後來,不斷的拓展發展成了 gnu compiler collection. 如果你用gcc編譯過fortran代碼的話,就會對後者了解的比較深刻了。現在的gcc可以看做是gnu支援的語言編譯器的前端。g++的設計目标是用來編譯C++程式代碼的,如期名字所暗示的那樣。是以,g++是一個c++ compiler,gcc是 compiler collection. 是以,可以推知g++的功能隻是gcc的一個子集。

         gcc可以用來編譯.cpp為字尾的c++程式源檔案,同樣g++也可以。你可能以為使用gcc編譯的時候,會調用g++。然而,并非如此!!!g++誕生的比gcc晚,剛誕生的g++事實上是用腳本語言寫的,其中将一系列的指令行參數傳給了gcc,是以應該說g++的内部調用了gcc。就版本的g++中,g++的實作腳本是用bash寫的。雖然現在的g++使用二進制可執行檔案寫的,但是内部原理還是一樣的。

         gcc和g++的具體差別有以下幾點:

l  對于.cpp為字尾的C++檔案,使用gcc編譯或者g++編譯效果差不多一樣的,但是連接配接的時候不同,g++會在連結的時候自動使用libstdc++,而gcc不會。

以下為實驗代碼:

/* 

* lib.cpp 

* a demo to show the difference between g++ and gcc , 

* when used to compile .cpp source files. 

* Author:Chaos Lee 

*/ 

#include<iostream> 

using namespace std; 

int main(int argc,char *argv[]) 

        cout<<"Hello world.\n"; 

        return 0; 

}       

                   接下來使用gcc編譯:

  [lichao@sg01 gccORg++]$ gcc lib.cpp -o lib 

/tmp/ccJLFgP9.o: In function `__static_initialization_and_destruction_0(int, int)': 

lib.cpp:(.text+0x23): undefined reference to `std::ios_base::Init::Init()' 

/tmp/ccJLFgP9.o: In function `__tcf_0': 

lib.cpp:(.text+0x66): undefined reference to `std::ios_base::Init::~Init()' 

/tmp/ccJLFgP9.o: In function `main': 

lib.cpp:(.text+0x81): undefined reference to `std::cout' 

lib.cpp:(.text+0x86): 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/ccJLFgP9.o:(.eh_frame+0x12): undefined reference to `__gxx_personality_v0' 

collect2: ld returned 1 exit status 

用紅色标示的部分标示連結器提示的錯誤,可以看出都是引用錯誤。接下來使用-lstdc++測試一下:

[lichao@sg01 gccORg++]$ gcc lib.cpp -o lib -lstdc++ 

[lichao@sg01 gccORg++]$ ./lib 

Hello world. 

OK. 

在使用g++測試一下:

[lichao@sg01 gccORg++]$ g++ lib.cpp -o lib 

由此驗證上述結論。

l  對于.c為字尾的源檔案,gcc預設使用c編譯器去編譯,而g++預設調用的是c++的編譯器。

這裡可以做一個簡單的實驗,用宏來測試一下:

測試代碼為:

* macro.c 

* a demo to show the difference between g++ and gcc, when used to compile 

* .c source files. 

* Author: Chaos Lee 

#include<stdio.h> 

int main(int argc,char *argv) 

#ifdef __cplusplus 

        printf("compiling with c++ compiler\n"); 

#else 

        printf("compiling with c compiler.\n"); 

#endif 

以下分别使用gcc和g++來測試(先驗了一下,哈哈):

[lichao@sg01 gccORg++]$ gcc macro.c -o macro 

[lichao@sg01 gccORg++]$ ./macro 

compiling with c compiler. 

[lichao@sg01 gccORg++]$ g++ macro.c -o macro 

         compiling with c++ compiler 

         由此驗證上述結論。

l  使用gcc和g++在編譯.cpp檔案時都會額外定義一些宏,這些宏在使用gcc編譯.c檔案時沒有的,這些宏包括:

 #define __GXX_WEAK__ 1 

#define __cplusplus 1 

#define __DEPRECATED 1 

#define __GNUG__ 4 

#define __EXCEPTIONS 1 

#define __private_extern__ extern 

本文轉自hipercomer 51CTO部落格,原文連結:http://blog.51cto.com/hipercomer/846923

繼續閱讀