Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template build error: Undefined symbols for architecture x86_64:

Tags:

c++

I am trying to use a template class and when I compile it in one file in LWS it works:

(Link is dead) ~http://liveworkspace.org/code/a9c412a7e683439dfa35a9363749369d~

But when I try to compile it made-up of 3 files,

stack.h lines 4 to 21

stack.cpp lines 24 to 48

main.cpp lines 49 to end

When I try to compile those 3 files I get

Undefined symbols for architecture x86_64:
  "Stack2<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::push(Node**, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)", referenced from:
      _main in ccCoizCT.o
  "Stack2<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::top(Node*&)", referenced from:
      _main in ccCoizCT.o
  "Stack2<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::pop(Node*&)", referenced from:
      _main in ccCoizCT.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status

Yes I have included stack.h in a stack.cpp and main.cpp files

like image 262
Jack F Avatar asked Oct 15 '12 23:10

Jack F


1 Answers

Sounds like you need to place the template definitions of stack back in the header file. Templates form a plan for code generation, so if the compiler can't see the entire template definition and only sees the declaration, code for that specific instantiations of the template will not be generated. It will simply trust the declaration and expect that at link time there exists an objects file with the instantiations of those templates. The solution to this is 1) keep the template definitions in the header file or 2) pre-generate the required definitions so the linker can find them at link time.

See here: Template issue causes linker error (C++)

like image 103
sashang Avatar answered Oct 22 '22 14:10

sashang