在我看来,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):
- g++ -o test.exe test.cpp
- gcc -o test.exe test.cpp -lstdc++
但是如果我尝试:
- gcc -o test.exe test.cpp
我在链接时得到 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;
}
使用以下命令编译并运行良好:
- gcc -o test.exe test.c
但是使用以下方式编译时会出现几个错误:
- g++ -o test.exe test.c
错误:
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/5853664/