g++找不到我的头文件

g++ does not find my header file?

本文关键字:文件 我的 找不到 g++      更新时间:2023-10-16

我正试图使用g++在树莓pi上用C++编译一个简单的程序。但是我不断地发现头文件不存在。我确信该文件确实存在,并且它也与源文件位于同一文件夹中。

有人知道吗?我已经报道了十几个谷歌搜索的前4页,但运气不好。

当我在正确的文件夹中时,我使用的命令是:

g++ -v -std=c++0x test.cpp timehandler.cpp -o Test

test.cpp:

#include <iostream>
#include "timehandler.h"
int main ()
{
    TimeHandler tOne("2015-12-12 20:00");
    TimeHandler tTwo("2015-12-12 21:00");
    cout << tOne.timeDiff(tTwo) << endl;
    return 0;
}

timehandler.cpp:

#include "timehandler.h"
using namespace std;
//Converts a timestring with "YYYY-MM-DD HH:MM:SS" to a time_t
TimeHandler::TimeHandler(std::string timeString)
{
  strptime(timeString.c_str(), "%Y-%m-%d %H:%M:%S", &mTimeInfo);
  mTime = mktime(timeInfo);
}
int TimeHandler::getTime()
{
  return mTime;
}
double TimeHandler::timeDiff(TimeHandler t)
{
    return difftime(this->getTime(),t.getTime());
}

timehandler.h:

#ifndef TIMEHANDLER_H
#define TIMEHANDLER_H
#include <string>
#include <time>
class TimeHandler
{
public:
    //Constructor
    TimeHandler(std::string timeString);
    //Public functions
    time_t getTime();
    double timeDiff(TimeHandler t);
private:
   //Private members
   struct tm mTimeInfo;
   time_t mTime;
};
#endif

试图编译代码时发现有几个错误:

  1. 返回类型不一致:

    在您的cpp文件中,您有:

    int TimeHandler::getTime()
    

    但这应该像你的头文件一样:

    time_t TimeHandler::getTime()
    
  2. 我还必须将#include <time>更改为ctime(或time.h):

    #include <ctime>
    
  3. 构造函数int TimeHandler::getTime()最后一行的参数不正确,应为:

    mTime = mktime(&mTimeInfo);
    
  4. 总的来说,您缺少coutendl(或using namespace std)的名称空间std

    std::cout << tOne.timeDiff(tTwo) << std::endl;
    
相关文章: