0

I have a Socket class as -

Socket(boost::asio::io_service& io_service, boost::asio::ip::tcp::endpoint ep);

I want the second param to be either a tcp or udp endpoint. For this, I have made the Socket class a template -

 Socket(boost::asio::io_service& ioService, T ep);

I then instantiate an object of Socket with -

boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address_v4::any(), 1235);  
Socket<boost::asio::ip::tcp::endpoint> obj(io_service, ep);

On compilation, I get the error:

(.text+0x96): undefined reference to `Socket<boost::asio::ip::basic_endpoint<boost::asio::ip::tcp> >::Socket(boost::asio::io_service&, boost::asio::ip::basic_endpoint<boost::asio::ip::tcp>)'

I have included the headers 'boost/asio.hpp' & 'boost/asio/ip/basic_endpoint.hpp' and compile using -lboost_system -lpthread -lboost_thread on Ubuntu 18.04 Virtual Box.

Could someone please help resolve this issue?

Edit:
Boost version - Boost version: 1.65.1

Build Command:

g++ ApplicationMain.cpp Socket.cpp -lboost_system -lpthread -lboost_thread -o output.out

I am pasting my code as is:


//*******Socket.h

template <typename T>
class Socket {
private:
    tcp::acceptor mAcceptor;

public:
    Socket(boost::asio::io_service& ioService, T ep);
};


//*******Socket.cpp

template <typename T>
Socket<T>::Socket(boost::asio::io_service& ioService, T ep): mAcceptor(ioService, ep)
{ 
}

//*******ApplicationMain.cpp

int main()
{
    printf("Main Start!\n");
    boost::asio::io_service io_service;

    boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address_v4::any(), 1235);
    Socket<boost::asio::ip::tcp::endpoint> obj(io_service, ep);

    return 0;
}
Rosh
  • 55
  • 5
  • 1
    Please show us the *exact* command you use to build. [Edit] your question and copy-paste (as text!) the command into it. – Some programmer dude Sep 28 '21 at 05:32
  • Also include the boost version you use. There has been some breaking changes in boost::asion over the years. – Ted Lyngmo Sep 28 '21 at 05:38
  • 1
    Possibly related (concerning your own template definitions): https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – πάντα ῥεῖ Sep 28 '21 at 05:49
  • Now when the error messages have been better formatted, it's easier to see that the problem is your own `Socket` class template. And it indeed looks like a duplicate of the question @πάνταῥεῖ linked to. – Some programmer dude Sep 28 '21 at 05:53
  • I believe, I have created the template class correctly. But there could be some mistake, its something I am unable to figure out :( – Rosh Sep 28 '21 at 06:09
  • Read the duplicate answers, either move your template class into the header file or use the workarounds to instantiate it in the cpp file – Alan Birtles Sep 28 '21 at 06:14
  • Adding the implementation to the header file, resolved my error. Thank you!!! – Rosh Sep 28 '21 at 06:35

0 Answers0