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

标签 gcc g++

在我看来,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/

相关文章:

c - 如何找到<值优化出来>的数组的地址?

c++ - “to_string”是't a member of “std”吗?

makefile - 如何使用 makefile 将 .o 和 .exe 文件放在/build/目录中

c++ - 静态库加载相关问题

c - 如何使用带有 Linux 子系统的 GCC 为 Windows 编译可执行文件?

gcc - ARM 程序集 : . LANCHOR0

c - 我在 C 中的动态队列显示无限奇怪的结果

cast 丢弃指针目标类型的限定符?

c++ - 在 solaris 上链接 zeromq 静态库

linux - 什么是 libg2c 库?