在我看来,gcc可以处理c和c++项目,那么为什么还需要g++/gcc-c++呢?
g++和gcc-c++之间有什么区别?
gcc
会根据文件扩展名将C源代码文件编译为C,将C++源代码文件编译为C++。但是它不会自动链接C++库。
g++
将自动包含C++库;默认情况下,它也会将扩展名指示为C源代码的文件编译为C++,而不是C。
来自http://gcc.gnu.org/onlinedocs/gcc/Invoking-G_002b_002b.html#Invoking-G_002b_002b:
C++源代码通常使用以下后缀之一:
.C
,.cc
,.cpp
,.CPP
,.c++
,.cp
, 或.cxx
;C++头文件通常使用.hh
,.hpp
,.H
, 或(用于共享模板代码).tcc
;预处理的C++文件使用后缀.ii
。GCC识别具有这些名称的文件,并将它们编译为C++程序,即使您像编译C程序一样调用编译器(通常使用gcc命令)。然而,使用gcc不会添加C++库。g++是调用GCC的程序,并将
.c
、.h
和.i
文件视为C++源文件而不是C源文件(除非使用了-x选项),并自动指定链接到C++库。当预编译带有.h
扩展名的C头文件以供C++编译时,此程序也很有用。
例如,要编译一个简单的C++程序,该程序向std::cout
流写入内容,可以使用以下任意一种方式(在Windows上使用MinGW):
但是如果我尝试这样做:
我会在链接时得到未定义的引用错误。
至于另一个差异,以下的C程序:
#include <stdlib.h>
#include <stdio.h>
int main()
{
int* new;
int* p = malloc(sizeof(int));
*p = 42;
new = p;
printf("The answer: %d\n", *new);
return 0;
}
使用以下命令编译和运行都没有问题:
但如果使用以下命令进行编译,则会产生多个错误:
错误信息:
test.c: In function 'int main()':
test.c:6:10: error: expected unqualified-id before 'new'
test.c:6:10: error: expected initializer before 'new'
test.c:7:32: error: invalid conversion from 'void*' to 'int*'
test.c:10:9: error: expected type-specifier before '=' token
test.c:10:11: error: lvalue required as left operand of assignment
test.c:12:36: error: expected type-specifier before ')' token