4

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()'.............................. ....................................

1
  • 1
    What @el.pescado said: Use g++ as linker instead of gcc, to get the links to the STL.
    – Medinoc
    Apr 25, 2014 at 10:48

1 Answer 1

16

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);
}
3
  • Thanks a lot . I used the method you told me , But I still got some errors.
    – ttworkhard
    Apr 25, 2014 at 10:03
  • 2
    You probably need to use g++, not gcc to link target executable. Apr 25, 2014 at 10:10
  • I added the wrapper declaration on the C end. Usually one puts them all in a header, with a macro EXTERN_C that would resolve to extern or extern "C" depending on language.
    – Medinoc
    Apr 25, 2014 at 10:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.