首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >“‘gettimeofday”不能用作函数

“‘gettimeofday”不能用作函数
EN

Stack Overflow用户
提问于 2020-09-25 03:00:54
回答 2查看 183关注 0票数 0

这里我遗漏了什么,这是我的主程序,我还有一个makefile,一切正常,错误就在这里的某个地方。

代码语言:javascript
复制
#include <iostream>
#include <observer.h>
#include <fstream>
using namespace std;

int main(int argc, char* argv[]) {
    std::fstream in;
    int gettimeofday;
    //CPUtypeandmodel
    struct timeval now;
    gettimeofday(&now, NULL);
    cout << "Status report as of : " << ctime((time_t*)&now.tv_sec) << endl;
    // Print machine name
    in.open("/proc/sys/kernel/hostname");
    string s;
    in >> s;
    cout << "Machine name: " << s << endl;
    in.close();

    return 1;
}  //end main

当我尝试创建该文件时,就会发生这种情况

代码语言:javascript
复制
observer.cpp: In function ‘int main(int, char**)’:
observer.cpp:13:26: error: ‘gettimeofday’ cannot be used as a function
   gettimeofday(&now, NULL);
                          ^
<builtin>: recipe for target 'observer.o' failed
make: *** [observer.o] Error 1
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-09-25 03:02:59

您将一个本地int变量命名为gettimeofday,这将防止您在三行之后调用函数gettimeofday()。别干那事。将该变量命名为其他名称,或者(考虑到它似乎未使用)直接删除它。

票数 6
EN

Stack Overflow用户

发布于 2020-09-25 03:28:56

您的int gettimeofday;正在隐藏具有相同名称的函数。您甚至不需要该变量,因此请删除它。

您需要在使用的函数和类中包含ctimesys/time.h

您打开文件/proc/sys/kernel/hostname进行写入,除非您以root身份运行该程序,否则该操作将失败。

转换为time_t*不是必需的,因为&now.tv_sec已经是一个time_t*

代码语言:javascript
复制
#include <sys/time.h>

#include <ctime>
#include <fstream>
#include <iostream>
#include <string>

int main() {
    // CPUtypeandmodel
    timeval now;

    if(gettimeofday(&now, nullptr) == 0)  // check for success
        std::cout << "Status report as of : " << std::ctime(&now.tv_sec) << '\n';

    // Print machine name
    if(std::ifstream in("/proc/sys/kernel/hostname"); in) { // open for reading
        std::string s;
        if(in >> s) // check for success
            std::cout << "Machine name: " << s << '\n';
    } // no need to call in.close(), it'll close automatically here

    return 1; // This usually signals failure. Return 0 instead.
} // end main
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64052773

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档