I am writting a "library" in C++ that is supposed to be used also by C code. I have followed the process as such:
- Using g++ and gcc compilers (as they are compatible).
- Used extern "C" in functions to be used by C code.
- My top level uses a wrapper function with signature that can be understood by a C compiler.
- Compiled to objective files the C++ code (with g++).
- Compiled my client code file with gcc.
- Edit: Tried/want to link them with gcc (or ld) (and not g++).
An MCV example would be the following:
mymalloc.h
#include <stdlib.h> /* for size_t */
#ifdef __cplusplus
extern "C"
#endif
void *mymalloc(size_t cbytes);
#ifdef __cplusplus
extern "C"
#endif
void myfree(void *ptr);
allocator.cpp
#include "allocator.h"
#include "mymalloc.h"
Allocator * Allocator::instance = 0;
extern "C" void *mymalloc(size_t cbytes){
Allocator *allocator = Allocator::getInstance();
return allocator->allocateFor(cbytes);
}
extern "C" void myfree(void *ptr){
Allocator *allocator = Allocator::getInstance();
allocator->freePtr(ptr);
}
...
That source file defines the functions to be used by C code, as well as methods of allocator.h which by itself includes other C++ stuff.
My C client file (cclient.c) is:
#include <stdio.h>
#include "mymalloc.h"
int main(void){
void *p = mymalloc(500);
printf("%p\n", p);
return 0;
}
I was under the impression that since I have those wrapper functions at my top level and since their declarations can be viewed by C code everything should be ok but I am getting linking errors: (sample/example shown)
./libmymalloc.a(allocator.o): In function `Allocator::getInstance()':
allocator.cpp:(.text+0x3cf): undefined reference to `operator new(unsigned long)'
allocator.cpp:(.text+0x3fa): undefined reference to `operator delete(void*, unsigned long)'
./libmymalloc.a(allocator.o):(.data.DW.ref.__gxx_personality_v0[DW.ref.__gxx_personality_v0]+0x0): undefined reference to `__gxx_personality_v0'
The way I am compiling and linking, in favor of clarity, is
g++ -c allocator.cpp
... (same for the rest .cpp files)
gcc -c cclient.c
gcc cclient.o allocator.o ...(all other c++ objectives)...
Edit (After first three answers): I know that I can link using g++. I would be interested in how to link with the C compiler, so that someone having available only gcc and the objectives (or a library from those) could link on his own.
(This question could be a duplicate, but I have read all other questions in SO and I couldn't deduct what I was doing wrong.)
allocator.h? And calling C++ code from C is really not a good idea.Allocatorclass andinclude's to other header (C++). Yes, I am aware of that.