Reputation: 875
I compiled a library which used g++
instead of 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.
What is the explanation? It was not the first time I met such a situation.
Upvotes: 8
Views: 24318
Reputation: 46998
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:
#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
Output:
/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++!
Upvotes: 23
Reputation: 5225
g++
automatically links the C++ runtime library—gcc
doesn't. Obviously, when it doesn't matter—then it doesn't matter, but, as already pointed out by spraff, it could be intended for future use.
Upvotes: 1
Reputation: 33405
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.
Upvotes: 3
Reputation: 5400
I don't know why they chose to use g++ instead of gcc, but I believe it shouldn't matter, as any valid C program is also valid C++.
Upvotes: -1