c++ - 从用户定义的头文件调用函数时出现 undefined reference 错误,它的实现在 .cpp 文件中

标签 c++ c++11 codeblocks linker-errors header-files

我做的是一个 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";
}

当这个codemain 中实现文件为:

#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
}

有一个linker error当我调用函数时 filename()fileSize() .

codeblocks出现以下错误:

undefined reference to fstreamExtension::fileName(std::string&)

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

最佳答案

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

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

关于c++ - 从用户定义的头文件调用函数时出现 undefined reference 错误,它的实现在 .cpp 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50371126/

相关文章:

c++ - Windows 中的按键事件

c++ - C++中 "this"关键字的使用问题

C++11 std::async 回调

c++ - WinRT C++ ComPtr GetAddressOf 与 &

c++ - 使用 CRTP 时在基类中使用非模板派生类的 typedef

c++ - std::thread 可以用在构造函数初始化列表中吗?

c++ - 为什么 Clang 和 VS2013 接受移动大括号初始化的默认参数,但不接受 GCC 4.8 或 4.9?

c - Pthread 程序在 Codeblocks 和 Linux Kernel 上打印不同的值

c++ - 代码::blocks中“No target”中的“no project”

c++ - 未找到 opencv .dll 文件