C++链接错误,我理解但无法解决

C++ Linking Errors, I understand but cannot solve it

本文关键字:解决 链接 错误 C++      更新时间:2023-10-16

我对C++还很陌生。我试图创建一个包含一些函数和类的库。

在visual studio解决方案中,我创建了另一个控制台项目,包括库,它在最初几次中起作用,但随着我创建了更多的源文件,链接器给了我未解析外部符号的LNK 2019错误。

我已经实现了头文件和类中的所有函数,可能会出现什么问题?这是我的包含

TS.h

/* I include "TS.h" in the console project */
#pragma once
#include "TMiscFunc.h"
#include "TFraction.h"

T馏分.h

#pragma once
#include <iostream>
#include "TMiscFunc.h"
namespace TS {
//The class which simulates a fraction
}

TFraction.cpp

#include "TFraction.h"
//Implementation of the functions of TFraction.h

TMiscFunc.h

namespace TS {

template <typename T0> T0 TAbsolute(T0 value);
template <typename T0> T0 TCeiling(T0 value);
template <typename T0> T0 TFloor(T0 value);
template <typename T0> T0 TPower(T0 value, int power);

TMiscFunc.cpp

#include "TMiscFunc.h"
template <typename T0> T0 TAbsolute(T0 value) {
//operations...
}
template <typename T0> T0 TCeiling(T0 value) {
//operations...
}
template <typename T0> T0 TFloor(T0 value) {
//operations...
}
template <typename T0> T0 TPower(T0 value, int power) {
//operations...
}

错误消息:

Error   LNK2019 unresolved external symbol "int __cdecl 
TS::TAbsolute<int>(int)" (??$TAbsolute@H@TS@@YAHH@Z) 
referenced in function "public: void __thiscall 
TS::TFraction::Simplify(void)" (? 
Simplify@TFraction@TS@@QAEXXZ)

所有的错误都是一样的,除了函数名称被更改了

感谢大家的阅读。

//解决

这里有一个最小的、完整的、可验证的例子来演示上述情况。它是基于Linux+gcc的,所以链接错误中的文本有点不同,但除此之外,它是一样的。以下是文件:

$ ls
Fraction.cpp  Fraction.h  Fraction_Int.h  main.cpp

及其内容:

$ cat Fraction.cpp
template<typename T0> T0 Floor(T0 value){ return value; }
$ cat Fraction.h
#ifndef __FRACTION_H__
#define __FRACTION_H__    
template<typename T0> T0 Floor(T0 value);    
#endif
$ cat Fraction_Int.h
#ifndef __FRACTION_INT_H__
#define __FRACTION_INT_H__    
class Fraction_Int {
public:
int nom;
int denom;
};    
#endif
$ cat main.cpp
#include "Fraction.h"
#include "Fraction_Int.h"
int main(int argc, char **argv)
{
Fraction_Int fi;
Floor<Fraction_Int>(fi);
return 0;
}

当我这样编译它时,我得到:

$ g++ -o main main.cpp Fraction.cpp
/tmp/cc4fLBk5.o: In function `main':
main.cpp:(.text+0x26): undefined reference to `Fraction_Int Floor<Fraction_Int>(Fraction_Int)'
collect2: error: ld returned 1 exit status

然后我把实现放在h文件中:

$ cat Fraction.h
#ifndef __FRACTION_H__
#define __FRACTION_H__
template<typename T0> T0 Floor(T0 value){ return value; }
#endif
$ cat Fraction.cpp
//template<typename T0> T0 Floor(T0 value){ return value; }

当我编译的时候一切都好。。。