56

I've been getting this undefined symbol building with this command line:

$ gcc test.cpp
Undefined symbols:
  "___gxx_personality_v0", referenced from:
  etc...

test.cpp is simple and should build fine. What is the deal?

ryan_s
  • 7,826
  • 3
  • 27
  • 28

4 Answers4

91

Use

g++ test.cpp

instead, since this is c++ code.


Or, if you really want to use gcc, add -lstdc++ to the command line, like so:

gcc test.cpp -lstdc++

Running md5 against the a.out produced under each scenario shows that it's the same output.

But, yeah, g++ probably makes your world a simpler place.

ryan_s
  • 7,826
  • 3
  • 27
  • 28
  • 2
    I though gcc was the front end that recognized cpp files and passed it through to the correct compiler. – paxdiablo Oct 15 '08 at 02:41
  • 14
    @Pax Diablo: Yes, it uses the correct _compiler_, however, g++ passes libstdc++ to the linker whereas gcc doesn't. :-P – C. K. Young Oct 15 '08 at 02:43
  • Right, it's a linker problem, not a compilation one. I normally don't build individual files from the command line like this, so I didn't even think and just typed gcc thinking it would work. – ryan_s Oct 15 '08 at 02:49
  • 4
    I've made that same mistake myself, at least twice that I can remember. :-) – Head Geek Oct 15 '08 at 03:04
  • 9
    This is not necessarily weariness or dumbness. I see lots of people answering to use g++ instead of gcc, but this is bad answer. The people asking and searching may not have that choice. I am working with libraries that have C and C++ versions, and I am writing a C program. Linking to some of these libraries made me have to link to stdc++, and I even had to specify with -L where to find it inside /usr/lib/gcc. – dividebyzero Dec 16 '11 at 03:58
  • Couldn't agree more with dividebyzero, combining C++ and C is not unheard of. Maybe your the dumb one. – SSH This Dec 13 '12 at 17:43
  • Works to compile PHP 5.3+fpm with `EXTRA_CFLAGS = -lstdc++` in Makefile – renedet Nov 07 '17 at 18:49
4

The .cpp extension causes gcc to compile your file as a C++ file. (See the GCC docs.)

Try compiling the same file, but rename it to have a .c extension:

mv test.cpp
gcc test.c

Alternatively, you can explicitly specify the language by passing -x c to the compiler:

gcc -x c -c test.cpp -o test.o

If you run nm test.o on these C-language versions, you'll notice that ___gxx_personality_v0 is not listed as a symbol.
(And if you run the same command on an object file generated with gcc -c test.cpp -o test.o, the ___gxx_personality_v0 symbol is present.)

chronospoon
  • 510
  • 6
  • 14
pseudosudo
  • 6,270
  • 9
  • 40
  • 53
3

Just in case anyone has the same problem as me: The file extension should be a .c not a .C (gcc is case-sensitive).

inket
  • 1,641
  • 16
  • 21
2

Had the same problem, but a different solution:

C++ code in static library getting linked, and being referenced by a .m file. Renaming the .m file to .mm fixed the issue.

BadPirate
  • 25,802
  • 10
  • 92
  • 123