0

For educational goals writing a class wrapper for sys/socket.

https://github.com/nkt/cpp-socket/blob/master/src/Socket.cpp#L94 - this is method. https://github.com/nkt/cpp-socket/blob/master/chat/main.cpp#L17 - this is usage.

So, XCode throws an error:

Undefined symbols for architecture x86_64:
  "Socket& operator<<<char const [16]>(Socket&, char const (&) [16])", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Although this code compiling and working fine:

#include <iostream>
#include <string>

class test
{
public:
    void send(std::string str);
    template <class T>
    friend test &operator <<(test &tst, T &message);
};

void test::send(std::string str)
{
    std::cout << str;
}

template <class T>
test &operator <<(test &tst, T &message)
{
    tst.send(std::string(message));
    return tst;
}

int main()
{
    test t;

    t << "hello world!\n";
}
user207421
  • 305,947
  • 44
  • 307
  • 483
nkt
  • 75
  • 1
  • 7
  • 5
    See [Why can templates only be implemented in the header file?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – dyp Apr 12 '14 at 19:48
  • 1
    Or http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix – chris Apr 12 '14 at 19:49
  • Why are you using templates here to begin with? – Ben Voigt Apr 12 '14 at 21:26

1 Answers1

0

You either need to move all templated class function definitions to your header file, or explicitly specialize your templates in the .cpp file.

niklasfi
  • 15,245
  • 7
  • 40
  • 54