从用户定义的头文件调用函数时出现未定义的引用错误,其实现位于.cpp文件中

undefined reference error while calling a function from user defined header file and it's implementation is in .cpp file

本文关键字:文件 错误 实现 引用 cpp 定义 用户 调用 函数 未定义      更新时间:2023-10-16

我做的是一个公开继承fstreamclassfstreamExtension类。

fstreamExtension.h :

#include <fstream>
#include <string>
#include <vector>
#ifndef FSTREAMEXTENSION_H
#define FSTREAMEXTENSION_H
class fstreamExtension : public std::fstream
{
private:
std::string fileIdentifier;
public:
using std::fstream::fstream;
using std::fstream::open;
~fstreamExtension();
inline void fileName (std::string&);
inline bool exists ();
inline unsigned long long fileSize();
};
#endif

fstreamExtension.cpp :

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "fstreamExtension.h"
inline void fstreamExtension::fileName (std::string& __fileIdentifier)
{
fileIdentifier = __fileIdentifier;
}
inline bool fstreamExtension::exists ()
{
if (FILE *file = fopen(fileIdentifier.c_str(), "r"))
{
fclose(file);
return true;
}
else
return false;
}

inline unsigned long long int fstreamExtension::fileSize()
{
if(exists())
{
std::ifstream tempStream(fileIdentifier.c_str(), std::ios::ate |  std::ios::binary);
unsigned long long int __size = tempStream.tellg();
tempStream.close();
return __size;
}
else return 0;
}
fstreamExtension::~fstreamExtension()
{
std::fstream::close();
std::cout << "stream closed";
}

当此code在文件中实现时main为 :

#include <iostream>
#include <fstream>
#include "fstreamExtension.h" 
int main()
{
string s = "QBFdata.txt";
fstreamExtension fs(s.c_str(), ios::in | ios::binary);
fs.fileName(s); //error
cout << fs.fileSize(); //error
}

当我调用函数filename()fileSize()时,有一个linkererror

codeblocks物种以下错误:

未定义对 fstreamExtension::fileName(std::string&( 的引用

感谢您的帮助,如果需要任何结构更改,请提出建议。

从函数声明和定义中删除inline以修复链接器错误。

inline对于头文件中定义的函数是有意义的。对于在其他位置定义的函数,inline使它们对其他翻译单元不可用,从而导致您观察到的链接器错误。