简体   繁体   English

模板构建错误:架构 x86_64 的未定义符号:

[英]Template build error: Undefined symbols for architecture x86_64:

I am trying to use a template class and when I compile it in one file in LWS it works:我正在尝试使用模板类,当我在 LWS 中的一个文件中编译它时,它可以工作:

(Link is dead) ~http://liveworkspace.org/code/a9c412a7e683439dfa35a9363749369d~ (链接已死)~http://liveworkspace.org/code/a9c412a7e683439dfa35a9363749369d~

But when I try to compile it made-up of 3 files,但是当我尝试编译它由 3 个文件组成时,

stack.h lines 4 to 21 stack.h 第 4 到 21 行

stack.cpp lines 24 to 48 stack.cpp 第 24 到 48 行

main.cpp lines 49 to end main.cpp 第 49 行到最后

When I try to compile those 3 files I get当我尝试编译这 3 个文件时,我得到

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是的,我在 stack.cpp 和 main.cpp 文件中包含了 stack.h

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 instantion 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 instantions of those templates.它将简单地信任声明并期望在链接时存在一个包含这些模板实例的对象文件。 The solution to this is 1) keep the template definitions in the header file or 2) pregenerate the required definitions so the linker can find them at link time.对此的解决方案是 1) 将模板定义保留在头文件中或 2) 预生成所需的定义,以便链接器可以在链接时找到它们。

See here: Template issue causes linker error (C++)请参阅此处: 模板问题导致链接器错误(C++)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM