nkn*_*ize 1 c++ compiler-construction linker
环顾四周,发现了一些类似的问题,但没有一个是相同的.大多数都与构造函数或析构函数有关.这个问题很可能是我生锈的C++链接器内存的结果(几年后重新启动).
我会保持简单,因为这可能是对链接器的基本误解:
data.h
#pragma once
namespace test {
class Data_V1 {
public:
// some getters/setters
int getData() { return _d; }
void setData( int d ) { _d = d; }
private:
// some data
int _d;
};
}
Run Code Online (Sandbox Code Playgroud)
builder.h
#pragma once
namespace test {
template <class V>
class Builder {
public:
void build();
};
}
Run Code Online (Sandbox Code Playgroud)
builder.cpp
#include <iostream>
#include "builder.h"
namespace test {
template<class V>
void Builder<V>::build() {
std::cout << "Insert building logic" << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
main.cpp中
#include "builder.h"
#include "data.h"
using namespace test;
int main(int argc, char* argv[]) {
Builder<Data_V1> b;
b.build();
}
Run Code Online (Sandbox Code Playgroud)
编译:
g++ -Wall -ansi -pedantic -c builder.cpp
g++ -Wall -ansi -pedantic -c main.cpp
g++ -Wall -ansi -pedantic -o main main.o builder.o
Run Code Online (Sandbox Code Playgroud)
链接错误:
Undefined symbols for architecture x86_64:
"test::Builder<test::Data_V1>::build()", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激!
模板定义需要对所有翻译单元可见.将定义从cpp标题移动到标题.
Builder.h
#pragma once
namespace test {
template <class V>
class Builder {
public:
void build();
};
template<class V>
void Builder<V>::build() {
std::cout << "Insert building logic" << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
在你问之前,不,除非你事先知道所有可能的专业,否则没有办法隐藏实现.
模板表示创建新类的通用形式.如果实现不可见,当您尝试专门化模板时,编译器无法知道要生成的代码.