代码之家  ›  专栏  ›  技术社区  ›  andreas buykx

如果C++函数名称重载,就找不到C++函数名了?

  •  1
  • andreas buykx  · 技术社区  · 15 年前

    我试图重写一个C样式的函数( func 在具有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确认了这两个函数确实都在库中。英特尔编译器和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";
    }
    
    1 回复  |  直到 15 年前
        1
  •  5
  •   Oliver Charlesworth    15 年前

    您已在中声明了函数 test.h 作为 int func(std::string) 但在 test.cpp 作为 int func(std::string &) . 看到区别了吗?