【问题标题】:Can I use C program function call C++ function while there is String type in C++ function parameter list?当 C++ 函数参数列表中有字符串类型时,我可以使用 C 程序函数调用 C++ 函数吗?
【发布时间】:2014-04-25 09:12:30
【问题描述】:

我的 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 tostd::ios_base::Init::Init()' hello.o:在函数__tcf_0': hello.cpp:(.text+0x6c): undefined reference tostd::ios_base::Init::~Init()' hello.o: 在函数fooCpp': hello.cpp:(.text+0x80): undefined reference tostd::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 tostd::allocator::~allocator()'的未定义引用............ ........... .....................................

【问题讨论】:

  • @el.pescado 所说:使用 g++ 作为链接器而不是 gcc,以获取到 STL 的链接。

标签: c++ c compiler-construction linker


【解决方案1】:

不。你需要用 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);
}

【讨论】:

  • 非常感谢。我用了你告诉我的方法,但还是出现了一些错误。
  • 您可能需要使用g++,而不是gcc 来链接目标可执行文件。
  • 我在 C 端添加了包装声明。通常将它们全部放在一个标题中,并使用宏 EXTERN_C 解析为 externextern "C",具体取决于语言。
猜你喜欢
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 2010-09-20
  • 1970-01-01
  • 1970-01-01
  • 2011-09-11
  • 2016-03-26
  • 2014-09-26
相关资源
最近更新 更多