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/55085451/

    相关文章:

    c++ - 在 c++/g++ 中提取 html 文件的外部链接

    c++ - 由于 libgmp.so.3,无法安装 local-build gcc-4.9.0

    reference - 奇怪的 g++ 链接行为取决于参数顺序

    c - 如何设置重复数据,使大部分可以优化掉?

    -std=c99 可以阻止我的#includes 正常工作吗?

    c++ - 警告 : 'auto' type specifier is a C++11 extension

    c++ - G++ 中的常量折叠

    optimization - 关于 g++ -O 选项

    c - 为 make 中的所有文件定义一个预处理器变量

    linux - Linux 中的“dlltool”等效项