My C program application needs to call C++ function . But there is string type in C++ function . For example ,I need to write a function fooC() like this:
//main.c:
void fooC()
{
char* str = "hello";
fooCPP(str);
}
//foo.cpp
void fooCPP(String& str)
{
......
}
How to write code correctly?
update
//hello.cpp
#include <iostream>
#include <string>
#include "hello.h"
using namespace std;
void fooCpp(char const* cstr){
std::string str(cstr);
cout << str <<endl;
}
//hello.h
#ifdef __cplusplus
extern "C"{
#endif
void fooCpp(char const* str);
#ifdef __cplusplus
}
#endif
//main.c
#include "hello.h"
int main()
{
char* str = "test" ;
fooCpp(str);
return 0;
}
compile:
g++ -c hello.cpp hello.h
gcc hello.o main.c -g -o main
error :
hello.o: In function __static_initialization_and_destruction_0(int, int)':
hello.cpp:(.text+0x23): undefined reference to
std::ios_base::Init::Init()'
hello.o: In function __tcf_0':
hello.cpp:(.text+0x6c): undefined reference to
std::ios_base::Init::~Init()'
hello.o: In function fooCpp':
hello.cpp:(.text+0x80): undefined reference to
std::allocator::allocator()'
hello.cpp:(.text+0x99): undefined reference to std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&)'
hello.cpp:(.text+0xa4): undefined reference to
std::allocator::~allocator()'..............................
....................................
Nope. You need to write a wrapper in C++:
//foo.cpp
void fooCPP(std::string& str)
{
......
}
extern "C" void fooWrap(char const * cstr)
{
std::string str(cstr);
fooCPP(str);
}
And call it from C:
/*main.c:*/
extern void fooWrap(char const * cstr); /*No 'extern "C"' here, this concept doesn't exist in C*/
void fooC()
{
char const* str = "hello";
fooWrap(str);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With