可能重复:
为什么模板只能在头文件中实现?
我最近一直在尝试使用C++.目前我正在尝试编写一些我确定至少已经完成过一次的东西:一个简单的LinkedList类.代码完成了,但我不知道怎么编译它.我一直在谷歌搜索,似乎我正在链接目标文件错误.这就是我的代码基本上是这样的:
TEST.CPP
#include "linkedlist.h"
int main()
{
LinkedList<int> list;
// do something
}
Run Code Online (Sandbox Code Playgroud)
linkedlist.h
template <typename T>
class LinkedList
{
// a lot of function and variable definitions
}
Run Code Online (Sandbox Code Playgroud)
然后是一个名为linkedlist.cpp的.cpp文件,其中包含LinkerList类的所有实际代码.尝试使用以下命令编译test.cpp时:
g++ ..\src\test.cpp
Run Code Online (Sandbox Code Playgroud)
我被告知有一个未定义的引用'LinkedList :: LinkedList()'.所以我一直认为它被链接错误,因为有多个.cpp文件,所以我尝试了这样:
g++ -c -Wall -O2 ..\src\test.cpp
g++ -c -Wall -O2 ..\src\linkedlist.cpp
g++ -s test.o linkedlist.o
Run Code Online (Sandbox Code Playgroud)
但是,这并没有改变任何事情.错误消息保持不变.我一直试图在互联网上找到一些信息,然而,它并没有真正解决.
一,问题:
主草图文件:
char foo; // required to clean up some other problems
#include <Arduino.h> // tried it in desperation, no help
#include "a.h"
void setup(){
Serial.begin(9600);
Serial.println("\nTest begins");
for (int num = -1; num < 1; num++){
Serial.print(num);
if (isNegative(num)){
Serial.println(" is negative");
} else {
Serial.println(" is NOT negative");
}
}
}
void loop(){}
Run Code Online (Sandbox Code Playgroud)
//啊
#ifndef H_A
#define H_A
boolean isNegative(int x); // Err#1
int anotherOdity();
#endif // H_A
Run Code Online (Sandbox Code Playgroud)
// a.cpp
#include "a.h"
int isNegative(int x){
Serial.println("I can't print …Run Code Online (Sandbox Code Playgroud)