Lauren
Lauren

Reputation: 11

‘gettimeofday’ cannot be used as a function

What am I missing here, this is my main program, I also have a makefile and everything works the error is somewhere in here.

#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

When I try and make the file this happens

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


                                                 

Upvotes: 0

Views: 1132

Answers (2)

Ted Lyngmo
Ted Lyngmo

Reputation: 117298

Your int gettimeofday; is shadowing the function with the same name. You don't even need that variable so remove it.

You need to include ctime and sys/time.h for the functions and classes you use.

You open the file /proc/sys/kernel/hostname for writing, which will fail unless you run the program as root.

The casting to time_t* is not necessary since &now.tv_sec is already a time_t*.

#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

Upvotes: 0

ShadowRanger
ShadowRanger

Reputation: 155418

You named a local int variable gettimeofday, which prevents you from calling the function gettimeofday() three lines later. Don't do that. Name the variable something else, or (given it seems unused) just get rid of it.

Upvotes: 6

Related Questions