我对C++还是个新手。我试图创建一个包含一些函数和类的库。
在visual studio解决方案中,我创建了另一个控制台项目,包括库,它在最初的几次中工作,但随着我创建更多的源文件,链接器给了我LNK 2019错误的未解决的外部符号。
我已经在我的头文件和类中实现了所有函数,还会出什么问题呢?下面是我的收录内容
TS.h
/* I include "TS.h" in the console project */
#pragma once
#include "TMiscFunc.h"
#include "TFraction.h"TFraction.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.hTMiscFunc.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)除了函数名被更改之外,所有的错误都是相同的
感谢大家的阅读。
//已解决
发布于 2018-07-27 12:09:23
这里是一个最小的、完整的和可验证的示例来演示上述情况。它是基于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; }当我编译一切都没问题的时候...
https://stackoverflow.com/questions/51550342
复制相似问题