在我看来,gcc可以处理c和c++项目,那么为什么需要g++/gcc-c++?
g++和gcc-c++有什么区别?
最佳答案
如果文件具有适当的扩展名,gcc
将C源文件编译为C,将C++源文件编译为C++。但是,它不会自动链接到C++库中。g++
将自动包括C++库;默认情况下,它还将编译带有扩展名的文件,这些扩展名指示它们是C源代码,而不是C语言。
从http://gcc.gnu.org/onlinedocs/gcc/Invoking-G_002b_002b.html#Invoking-G_002b_002b:
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 treats
.c
,.h
and.i
files as C++ source files instead of C source files unless -x is used, and automatically specifies linking against the C++ library. This program is also useful when precompiling a C header file with a.h
extension for use in C++ compilations.
例如,要编译写入
std::cout
流的简单C++程序,我可以使用其中一个(在Windows上为MinGW):但是,如果我尝试:
我在链接时得到 undefined reference 。
而另一个不同之处是以下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
关于gcc - gcc和g++/gcc-c++有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55085451/