gcc
如果文件具有适当的扩展名,则将 C 源文件编译为 C,将 C++ 源文件编译为 C++;但是它不会自动链接到 C++ 库中。
g++
将自动包含 C++ 库;默认情况下,它还会将带有扩展名的文件编译为 C++,而不是 C。
From http://gcc.gnu.org/onlinedocs/gcc/Invoking-G_002b_002b.html#Invoking-G_002b_002b:
C++ 源文件通常使用以下后缀之一.C
, .cc
, .cpp
, .CPP
, .c++
, .cp
, or .cxx
; C++经常使用的头文件.hh
, .hpp
, .H
,或(对于共享模板代码).tcc
;预处理的 C++ 文件使用后缀.ii
。即使您以与编译 C 程序相同的方式调用编译器(通常使用名称 gcc),GCC 也会识别具有这些名称的文件并将它们编译为 C++ 程序。
但是,使用gcc并不会添加C++库。 g++是一个调用GCC并处理的程序.c
, .h
and .i
除非使用 -x,否则将文件视为 C++ 源文件而不是 C 源文件,并自动指定针对 C++ 库的链接。当使用以下命令预编译 C 头文件时,该程序也很有用.h
用于 C++ 编译的扩展。
例如,编译一个简单的 C++ 程序,写入std::cout
流,我可以使用其中一个(Windows 上的 MinGW):
- g++ -o test.exe test.cpp
- gcc -o test.exe test.cpp -lstdc++
但如果我尝试:
我在链接时得到未定义的引用。
对于其他区别,以下 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;
}
使用以下命令编译并运行良好:
但使用编译时会出现几个错误:
Errors:
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