What's the difference between gcc and g++/gcc

It seems to me that gcc can deal with both c and c++ projects,so why is g++/gcc-c++ needed?

What's the difference between g++ and gcc-c++?


gcc will compile C source files as C and C++ source files as C++ if the file has an appropriate extension; however it will not link in the C++ library automatically.

g++ will automatically include the C++ library; by default it will also compile files with extensions that indicate they are C source as C++, instead of as C.

From 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.

For example, to compile a simple C++ program that writes to the std::cout stream, I can use either (MinGW on Windows):

  • g++ -o test.exe test.cpp
  • gcc -o test.exe test.cpp -lstdc++
  • But if I try:

  • gcc -o test.exe test.cpp
  • I get undefined references at link time.

    And for the other difference, the following C program:

    #include <stdlib.h>
    #include <stdio.h>
    
    int main() 
    {
        int* new;
        int* p = malloc(sizeof(int));
    
        *p = 42;
        new = p;
    
        printf("The answer: %dn", *new);
    
        return 0;
    }
    

    compiles and runs fine using:

  • gcc -o test.exe test.c
  • But gives several errors when compiled using:

  • g++ -o test.exe test.c
  • Errors:

    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
    

    据我所知,g ++使用正确的C ++链接器选项,而gcc使用C链接器选项(所以你可能会得到未定义的引用等)。

    链接地址: http://www.djcxy.com/p/15040.html

    上一篇: 如何在Mac OS X 10.8 / Xcode 4.4上使用/安装gcc

    下一篇: gcc和g ++ / gcc有什么区别