[英]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.