1

I tried the following code in C as well as C++ .file1 is a c file .file2 is a c++ file and file3 is a header file for name magling.

file1.c

#include<stdio.h>
#include<stdlib.h>
#include "file3.hpp"

int main(int argc,char **argv)
{
int a[5];
int i;
for(i=0;i<5;i++)
    a[i] = i;
printf("%d",a[17]);
return 0;
}

file2.cpp

#include "file3.hpp"

int printtrial(int number)
{
return number;
}

file3.hpp

#ifdef __cplusplus
extern "C"
{
#endif

extern int printtrial(int number);

#ifdef __cplusplus
}
#endif

I compile it using the following commands:

gcc -c file1.c
g++ -c file2.cpp
gcc -o output file1.o file2.o

On this it gives the error:

file2.o:(.eh_frame+0x12): undefined reference to `__gxx_personality_v0'
collect2: ld returned 1 exit status

Can anyone tell me what's going on!

mu is too short
  • 426,620
  • 70
  • 833
  • 800
station
  • 6,715
  • 14
  • 55
  • 89
  • To study the root of the problem, you can use command `nm` or `objdump -t` to list the symbols in `.o` files, then you will see the truth. In fact, your code in my environment (MinGW on windows) works well, because file2.o doesn't include redundant symbols. – Stan Jul 22 '11 at 11:05
  • Re "`printf("%d",a[17])`" : `a` is declared as `int a[5];` so `a[17]` is undefined behavior. Re "file2 is a c++ file and file3 is a header file for name magling" : file3 is **not** a header file for name mangling. It prevents name mangling. It forces g++ to treat `printtrial()` as a C function. BTW, it is "name mangling", not "name magling". When you typed that question the word "magling" should have appeared with a red underline. That means it is a misspelled word. Pay attention to that! – David Hammen Jul 22 '11 at 12:23

2 Answers2

7

As one of your files is compiled as c++ use g++ for linking phase.

See: What is __gxx_personality_v0 for?

Community
  • 1
  • 1
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
2

C and C++ executables require the presence of some libraries, which are included during the linking stage:

gcc -o output file1.o file2.o

The problem here is that you are trying to link a C++ file using a C linker. gcc simply fails to locate some libraries required by the C++ runtime. To solve this you must use g++, like yi_H said.

nmat
  • 7,430
  • 6
  • 30
  • 43