C++链接错误,我理解但无法解决
C++ Linking Errors, I understand but cannot solve it
我对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; }
当我编译的时候一切都好。。。
相关文章:
- 未解决的外部链接问题
- Clang 8 带有静态 constexpr 和数组的链接器错误 - 错误是什么以及如何解决它?
- 调用运算符时出现链接器错误<<,如何解决?
- 在Embarcadero C++ Builder中生成的DLL未解决的外部链接错误
- mapreduce c编程与-fPIC链接失败,如何解决?
- 当只有静态方法受到影响时,如何解决C++中的链接器错误?
- C++链接错误,我理解但无法解决
- 将单元测试添加到旧解决方案时出现链接错误
- 在可视化解决方案 c++ 中获取链接器错误
- 在将QT与Cmake一起使用时解决链接错误
- C - 使用静态和动态库时解决链接器错误
- 更改参数的顺序可解决链接器错误
- 尝试解决链接器警告:默认库'MSVCRT'与使用其他库冲突
- 如何使用libcurl解决链接中未定义的引用错误
- 使用 JNI 将 C# 加载到 Java 项目中的未解决链接错误
- 我在尝试在类中创建对象时面临如何解决链接错误
- 需要帮助解决链接器错误LNK2001 Visual Studio 2010
- 链接器如何解决链接*.lib时的歧义
- QT Creator配置更改以解决链接错误
- 解决链接器错误:对静态类成员的未定义引用