c++ - C++函数参数表中有String类型的情况下,是否可以使用C程序函数调用C++函数?

标签 c++ c compiler-construction linker

我的 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 你好.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::allocator::~allocator()'................................ .....................................

最佳答案

没有。您需要用 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);
}

关于c++ - C++函数参数表中有String类型的情况下,是否可以使用C程序函数调用C++函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23288874/

相关文章:

c++ - 使用智能指针作为 Qt 标准函数的参数

java - 为什么我必须在它定义的类中导入嵌套类?

c++ - 带有调试选项的 gcc 编译阶段

windows - 您可以将 OCaml 项目本地编译为 Windows 库吗?

c++ - 什么是 "cache-friendly"代码?

c++ - 文件创建时间的 std::filesystem::last_write_time() 等价物在哪里?

c++ - 整数阈值

c - linux cp命令实现复制多个文件到一个目录

c - 更新 CLOB 后出现 ORA-3113

c - 尝试使用 execvpe(...) 但出现隐式声明错误 - 尽管我认为我使用的是正确的参数类型