gcc和g ++/gcc-c ++有什么区别?

gdb*_*gdb 28 gcc g++

在我看来,gcc可以处理c和c ++项目,那么为什么需要g ++/gcc-c ++呢?

g ++和gcc-c ++有什么区别?

Mic*_*urr 55

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++源文件通常使用后缀之一.C,.cc,.cpp,.CPP,.c++,.cp,或.cxx; C++头文件经常使用.hh,.hpp,.H,或(用于共享模板代码).tcc; 和预处理的C++文件使用后缀.ii.GCC识别具有这些名称的文件并将它们编译为C++程序,即使您以与编译C程序相同的方式调用编译器(通常使用名称gcc).

但是,使用gcc不会添加C++库.克++是调用GCC和治疗程序.c,.h.i文件作为C++源文件而不是C源文件,除非-x被使用,并且自动指定链接到的C++库.当预编译带有.h扩展的C头文件以在C++编译中使用时,此程序也很有用.

例如,要编译一个写入std::cout流的简单C++程序,我可以使用(Windows上的MinGW):

  • g ++ -o test.exe test.cpp
  • gcc -o test.exe test.cpp -lstdc ++

但如果我尝试:

  • gcc -o test.exe test.cpp

我在链接时获得了未定义的引用.

而对于其他差异,以下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;
}
Run Code Online (Sandbox Code Playgroud)

编译并运行正常使用:

  • 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
Run Code Online (Sandbox Code Playgroud)

  • 因为它使用"new"作为变量名,ho ho. (6认同)
  • 什么样的程序员使用“new”作为变量名?我更想知道的是,您是如何使用 gcc 成功编译该可憎的... (2认同)
  • @JohnJohn 这只是一个有效的 C(但无效的 C++)代码的例子,这就是 gcc 编译它的原因。 (2认同)