- Why use g++ instead of gcc?
- Why some codes compile with g++ but not in gcc?
- How do we know what compiler works fine with our code?
- Background of gcc and g++ compilers
gcc
/ g++
is just a front-end driver programs which invokes the actual compiler and / or linker based on the options given to it.
If you invoke the compiler as gcc
:
- it will compile as C or C++ based on the file extension (
.c
, or.cc
/.cpp
); - it will link as C, i.e. it will not pull in C++ libraries unless you specifically add additional arguments to do so.
If you invoke the compiler as g++
:
- it will compile as C++ regardless of whether or not the file extension is
.c
or.cc
/.cpp
; - it will link as C++, i.e. automatically pull in the standard C++ libraries.
2. Examples you may face the difference between g++ and gcc
$ gcc -o test test.c
$ g++ -o test test.c
This will compile with gcc, but not with g++ and give some errors. C++ requires an explicit cast from void*
here, whereas C does not.
This will give errors when compile using gcc. (because of ‘int array’ – it is not recognized in c linking stage)
we can prove it by compiling using gcc and then linking with g++
$ gcc –c test.c
$ g++ –o test test.o
$ ./test
- Where as g++ not compile .c ass plain C, it always compiles as c++.
g++
automatically links the C++ runtime library wheregcc
doesn't.