Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new and delete in a c++ library being called from a C program

Tags:

c++

c

gcc

g++

I have a series of c++ classes stored in a library with a C interface (see example below). And I have a C program that includes this c++ libary via the C interface. This seems to work well until I tried to create a class in the libary with new and delete.

I am using gcc to compile the C code and g++ for the C++ libary, I crated the projects with Eclipse on unbunu.

The error message that I get is

undefined reference to 'operator new(unsigned int)' 
undefined reference to 'operator delete(void*)' 

Libary H file

#ifndef CFOO_H_
#define CFOO_H_
#ifdef __cplusplus

class CBar {
   public:
      int i ; 
};

class CFoo {
   public:
      int work();
};
extern CFoo g_foo ;
extern "C" {
#endif /* __cplusplus */    
   int foo_bar( ) ;    
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CFOO_H_ */

Libary cpp file

#include "CFoo.h"
CFoo g_foo ;

int CFoo::work() {
   CBar * b = new CBar(); 
   delete b; 
   return 1; 
}

int foo_bar( ) {
   return g_foo.work( );
}

Main c file

void * __gxx_personality_v0 ;
int main(void) {
printf( "foo_bar 10   =%d\n", foo_bar() ) ;
     return 0; 
}

I have tried a few things with out success, any thoughts?

Edit

It looks like it was a problem with the auto generated make files produced by Eclipse. Once I manualy changed the C applcations makefile to link with g++ instead of gcc I was able to build the applcation. See comments below for more information.

like image 539
Steven Smethurst Avatar asked May 03 '11 18:05

Steven Smethurst


People also ask

What is new and delete operator in C?

These operators allocate memory for objects from a pool called the free store (also known as the heap). The new operator calls the special function operator new , and the delete operator calls the special function operator delete .

Why overload new and delete?

The most common reason to overload new and delete are simply to check for memory leaks, and memory usage stats. Note that "memory leak" is usually generalized to memory errors. You can check for things such as double deletes and buffer overruns.

What is difference between new () and malloc ()?

malloc(): It is a C library function that can also be used in C++, while the “new” operator is specific for C++ only. Both malloc() and new are used to allocate the memory dynamically in heap. But “new” does call the constructor of a class whereas “malloc()” does not.

What is delete in C programming?

The remove function in C/C++ can be used to delete a file. The function returns 0 if files is deleted successfully, other returns a non-zero value. #include<stdio.h> int main() {


1 Answers

Quoting unapersson: It's not linking in the C++ runtime. You should use "g++" as the link command, rather than "gcc".

like image 157
2 revs Avatar answered Sep 30 '22 07:09

2 revs