why use g++ instead of gcc to compile *.cc files?
I compiled a library which use the g++ instead gcc. First I thought the source code was written in C++ but I found out later that there was not any C++ code in the *.cc files.
To confirm this, I replaced the g++ in the original makefile with gcc. And I still got the correct program.
Anyone can explain this? It was not the first time I met such a situation.
It depends on what exactly you changed in the makefile. gcc
/ g++
is really just a front-end driver program which invokes the actual compiler and / or linker based on the options you give it.
If you invoke the compiler as gcc
:
.c
, or .cc
/ .cpp
); If you invoke the compiler as g++
:
.c
or .cc
/ .cpp
; (see the relevant bit of the GCC documentation).
Here's a simple program which detects whether or not it has been compiled as C or C++.
(It makes use of the fact that a character constant has the size of an int
in C, or a char
in C++. sizeof(char)
is 1 by definition; sizeof(int)
will generally be larger - unless you're using an obscure platform with >= 16-bit bytes, which you're probably not.)
I've called it test.c
and copied it as test.cc
as well:
$ cat test.c
#include <stdio.h>
int main(void)
{
printf("I was compiled as %s!n", sizeof('a') == 1 ? "C++" : "C");
return 0;
}
$ cp test.c test.cc
$
Compiling and linking test.c
with gcc
, and test.cc
with g++
, works as expected:
$ gcc -o test test.c
$ ./test
I was compiled as C!
$ g++ -o test test.cc
$ ./test
I was compiled as C++!
$
Compiling and linking test.cc
with gcc
doesn't work: it compiles the code as C++ because the file ends in .cc
, but fails at the link stage:
$ gcc -o test test.cc
/tmp/ccyb1he5.o:(.eh_frame+0x11): undefined reference to `__gxx_personality_v0'
collect2: ld returned 1 exit status
$
which we can prove by separately compiling with gcc
, and linking with g++
(to pull in the right libraries):
$ gcc -c test.cc
$ g++ -o test test.o
$ ./test
I was compiled as C++!
$
... gcc
has compiled the code as C++ rather than C, because it had a .cc
file extension.
Whereas g++
does not compile .c
files as plain C:
$ g++ -o test test.c
$ ./test
I was compiled as C++!
$
It could be that the .cc code happens to be C, but was intended to be linked into a C++ library. The internals are different.
g++
automatically links the C++ runtime library — gcc
doesn't. Obvoiusly, when it doesn't matter — then it doesn't matter, but, as already pointed out by spraff, it could be intended for future use.
上一篇: 链接库与gcc:参数的顺序