Linux 下 gcc 与 g++的差别
以下来自官方文档说明
3.3 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’, ‘.hpp’, ‘.H’, or (for shared template code) ‘.tcc’; 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 automatically specifies linking against the C++ library. It treats ‘.c’, ‘.h’
and ‘.i’ files as C++ source files instead of C source files unless -x is used. 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++
.
When you compile C++ programs, you may specify many of the same command-line options that you use for compiling programs in any language; or command-line options meaningful for C and related languages; or options that are meaningful only for C++ programs. See Options Controlling C Dialect, for explanations of options for languages related to C. See Options Controlling C++ Dialect, for explanations of options that are meaningful only for C++ programs.
以下转自
首先编写了第一个C++程序,Hello,world!
#include <iostream>
using namespace std;
void main()
...{
cout << "Hello,world!" <<endl;
return;
}
用命令:GCC -o test test.cpp编译,有问题。然后分析,即分开运行GCC.
GCC -c -o test.o test.cpp。成功执行。
GCC -o test test.o。出现一堆链接错误。
g++ -o test test.o。成功执行。
由此发现,GCC与g++还有有一些区别的。
GCC and g++分别是gnu的c & c++编译器 GCC/g++在执行编译工作的时候,总共需要4步
1 :两者都可以编译C和C++代码,但是请注意:
(1).后缀为.c的,GCC把它当作是C程序,而g++当作是c++程序;后缀为.cpp的,两者都会认为是c++程序,注意,虽然c++是c的超集,但是两者对语法的要求是有区别的。C++的语法规则更加严谨一些。
(2).编译阶段,g++会调用GCC,对于c++代码,两者是等价的,但是因为GCC命令不能自动和C++程序使用的库联接,所以通常用g++来完成链接,为了统一起见,干脆编译/链接统统用g++了,这就给人一种错觉,好像cpp程序只能用g++似的。
2 :对于__cplusplus宏,实际上,这个宏只是标志着编译器将会把代码按C还是C++语法来解释,如上所述,如果后缀为.c,并且采用GCC编译器,则该宏就是未定义的,否则,就是已定义。
以下转自
http://blog.****.net/gmpy_tiger/article/details/47808081
参考网易博客者“静心”的博客——《gcc与g++的区别》结合自己的认识做出的个人领悟。(由于个人水平有限,难免会存在错误的地方,请见谅)
一般而言,在Linux下编译程序分为以下4个阶段:
- 预处理:编译处理宏定义等宏命令(eg:#define)——生成后缀为“.i”的文件
- 编译:将预处理后的文件转换成汇编语言——生成后缀为“.s”的文件
- 汇编:由汇编生成的文件翻译为二进制目标文件——生成后缀为“.o”的文件
- 连接:多个目标文件(二进制)结合库函数等综合成的能直接独立执行的执行文件——生成后缀为“.out”的文件
- 后缀为.c的,gcc把它当作是C程序(cc/cpp才判定为C++源程序),而g++当作是c++程序
- gcc无法进行库文件的连接,即无法编译完成步骤4;而g++则能完整编译出可执行文件。(实质上,g++从步骤1-步骤3均是调用gcc完成,步骤4连接则由自己完成)
- gcc -E 执行到步骤1,只处理宏命令,需要用重定向生成文件
- gcc -S 执行到步骤2,生成文件.s
- gcc -c 执行到步骤3,生成文件.o
- g++ 分别编译于连接 .cc文件与.o文件
- #include <iostream>
- using namespace std;
- int main()
- {
- cout<<"This is a C++ program."<<endl;
- }
- gcc -E 1.cc >> 1.i
- vi 1.i
- gcc -S 1.cc
- vi 1.s
- gcc -c 1.cc
- g++ 1.o -o from_o
运行结果:
- g++ 1.cc -o from_cc
运行结果:
- gcc 1.cc