![](/img/trans.png)
[英]Function defined in the header and called from the cpp file error
[英]undefined reference error while calling a function from user defined header file and it's implementation is in .cpp file
我所做的是一个fstreamExtension
类,该类公开继承了fstream
class
。
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()
时,出现linker
error
。
codeblocks
产生以下错误:
未定义对fstreamExtension :: fileName(std :: string&)的引用
感谢您的帮助,请提出是否需要任何结构更改的建议。
从函数声明和定义中删除inline
以修复链接器错误。
inline
对于头文件中定义的功能有意义。 对于其他地方定义的函数, inline
使其无法用于其他翻译单元,从而导致您观察到链接器错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.