Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use C program function call C++ function while there is String type in C++ function parameter list?

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 tostd::ios_base::Init::Init()' hello.o: In function __tcf_0': hello.cpp:(.text+0x6c): undefined reference tostd::ios_base::Init::~Init()' hello.o: In function fooCpp': hello.cpp:(.text+0x80): undefined reference tostd::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 tostd::allocator::~allocator()'.............................. ....................................

like image 497
ttworkhard Avatar asked Dec 05 '22 06:12

ttworkhard


1 Answers

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);
}
like image 190
Medinoc Avatar answered Dec 09 '22 14:12

Medinoc