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