[英]Can I use C program function call C++ function while there is String type in C++ function parameter list?
我的C程序应用程序需要调用C ++函数。 但是C ++函数中有字符串类型。 例如,我需要像这样写一个函数fooC():
//main.c:
void fooC()
{
char* str = "hello";
fooCPP(str);
}
//foo.cpp
void fooCPP(String& str)
{
......
}
如何正确编写代码?
更新
//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;
}
编译:
g ++ -c hello.cpp hello.h
gcc hello.o main.c -g -o main
错误 :
hello.o:函数__static_initialization_and_destruction_0(int, int)': hello.cpp:(.text+0x23): undefined reference to
std :: ios_base :: Init :: Init()'hello.o:函数__tcf_0': hello.cpp:(.text+0x6c): undefined reference to
std :: ios_base :: Init :: ~Init()'hello.o:在函数fooCpp': hello.cpp:(.text+0x80): undefined reference to
std :: allocator :: allocator()'hello.cpp :(。text + 0x99):对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::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 :: ~addocation()'......... ..................... ............................. .......
不。 你需要用C ++编写一个包装器:
//foo.cpp
void fooCPP(std::string& str)
{
......
}
extern "C" void fooWrap(char const * cstr)
{
std::string str(cstr);
fooCPP(str);
}
并从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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.