Question

I was trying to override a C-style function (func) in a library with a C++ style function accepting different arguments, as the code below demonstrates.

I compiled test.cpp into a shared library libtest.so, and compiled main.cpp and linked it with the libtest.so library. This all works, upto the linking step, where I get undefined reference to 'func(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'.

Can someone explain me why the linker cannot resolve the C++ function? I checked with nm that both functions are indeed in the library. The linker error occurs both with intel and g++ compilers.

test.h:

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

test.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();
}

main.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";
}
Was it helpful?

Solution

You've declared the function in test.h as int func(std::string), but defined it in test.cpp as int func(std::string &). See the difference?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top