I hit my head about it a couple of times, looking through it and looking for similar code in open source projects: I can’t find what I'm doing wrong.
Essentially, given the code below (inherently overridden):
#include <iostream> using std::cout; using std::endl; using std::string; template <typename T> class Node { T value_; public: Node(const T& value) : value_(value) {} T const value() const { return value_; } friend std::ostream& operator <<(std::ostream& out, const Node<T>& node); Node<T> operator +(const Node<T>& other) { return Node(value() + other.value()); } }; template <typename T> std::ostream& operator <<(std::ostream& out, const Node<T>& node) { return out << node.value(); }
when used in code, for example:
int main(int argc, char* argv[]) { Node<string> node("node X"); cout << node << endl; Node<int> three(3); cout << three << endl; return EXIT_SUCCESS; }
I get the following linker error:
Undefined symbols for architecture x86_64: "operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, Node<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > const&)", referenced from: _main in StlPractice.cpp.o "operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, Node<int> const&)", referenced from: _main in StlPractice.cpp.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)
As far as I can tell, this is all legal C ++ 11 code; the template is well defined, and yet it seems to somehow avoid the linker being able to find it.
This is built using cmake on OS X:
cmake_minimum_required(VERSION 3.3) project(simple_template) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") set(SOURCE_FILES src/simple_template.cpp) add_executable(simple ${SOURCE_FILES})
What gives?
Thanks in advance!
Update . Following this question, I also performed the following, same result:
$ clang++ src/simple_template.cpp Undefined symbols for architecture x86_64: "operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, Node<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > const&)", referenced from: _main in StlPractice-e20370.o "operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, Node<int> const&)", referenced from: _main in StlPractice-e20370.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)