1

我试图func用接受不同参数的 C++ 风格函数覆盖库中的 C 风格函数 ( ),如下面的代码所示。

我将 test.cpp 编译成一个共享库 libtest.so,并编译 main.cpp 并将其与 libtest.so 库链接。这一切都有效,直到我得到的链接步骤 undefined reference to 'func(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'

有人可以解释一下为什么链接器无法解析 C++ 函数吗?我用 nm 检查了这两个函数确实在库中。intel 和 g++ 编译器都会出现链接器错误。

测试.h:

extern "C" {
int func( char* str, int size  );
}
#include <string>
int func( std::string str );

测试.cpp:

#include <stdio.h>
#include <string>
#include "test.h"

int func( char *buf, int size )
{
   return snprintf( buf, size, "c-style func" );
}

int func( std::string& str )
{
    str = "c++-style func";
    return str.size();
}

主.cpp:

#include <iostream>
#include <string>
#include "test.h"

int main()
{
   char buf[1024];
   func( buf, 1024 );
   std::cout << buf << "\n";

   std::string str;
   func( str );
   std::cout << str << "\n";
}
4

1 回答 1

5

您已经在 as 中声明了函数,但在test.has中定义了它。看到不同?int func(std::string)test.cppint func(std::string &)

于 2010-11-09T11:58:51.240 回答