I am trying to run the following code snippet taken from this simple example of a timer:
#include <sys/time.h>
#include <stdio.h>
int SetTimer(struct timeval &tv, time_t sec) {
gettimeofday(&tv, NULL);
tv.tv_sec += sec;
return 1;
}
int CheckTimer(struct timeval &tv, time_t sec) {
struct timeval ctv;
gettimeofday(&ctv, NULL);
if ((ctv.tv_sec > tv.tv_sec)) {
gettimeofday(&tv, NULL);
tv.tv_sec += sec;
return 1;
} else {
return 0;
}
}
int main() {
struct timeval tv;
SetTimer(tv, 5); //set up a delay timer
printf("start counting.\n");
while (1)
if (CheckTimer(tv, 5) == 1)
printf("Welcome to cc.byexamples.com\n");
return 0;
}
I am obtaining the following error: field tv_sec could not be resolved
I have searched for it on the Web but no one seems to give a concrete answer.
I tried my chance looking into the libraries sys/time.h and time.h but in none of them seems to be defined this structure but is anyway used.
Am I missing any library? Since this example is rather old, did something changed that needs it to be done in a different way? I would appreciate any sight.
PS: I am using Eclipse CDT Indigo under Ubuntu 11.10 and g++ 4.6.1.
try to put this in your file : #define __USE_GNU
In the end it was an Eclipse problem since it was unable to index the time.h library. I solved it by following the most upvoted answer of this other SF question:
Adding manually time.h to the C/C++ indexer.
Currently I am using Eclipse CDT Juno and the problem doesn't seems not to be happening anymore. As a side comment in Eclipse CDT Juno I couldn't find the location where to manually edit the C/C++ indexer settings.
Related
I'm having problems with st_size of stat struct in a simple program for Raspberry Pi.
I write the code in Eclipse C/C++ IDE (CDT) with a Macbook, and then compile it in the Raspberry Pi. I didn't have problems until I started using fstat and stat structure.
I test this code in Raspberry Pi and it work fine.
#include <stdio.h>
#include <arm-linux-gnueabihf/sys/stat.h>
#include <unistd.h>
int main(void) {
FILE *pFile;
struct stat buf;
pFile = fopen("File.bin","rb");
if ( pFile != 0 ) {
fstat(fileno(pFile), &buf);
printf("File size: %d\n", buf.st_size);
//printf("File size: %d\n", buf.stat);
fclose(pFile);
}
return 0;
}
The problem is when I tried to use buf.st_size the Eclipse throws Field 'st_size' could not be resolve. Instead, the Eclipse autocomplete with '.stat' like the commented line (buf.stat).
So far, I added in "C/C++ General -> Paths and Symbols -> Includes" the path where I copied the includes "stat.h" obtained from the "Raspberry Pi".
I can't make "Field 'st_size' could not be resolve" problem go away.
Any suggestion would be appreciate!
Thank you for your time
I am doing a cross compilation test in Eclipse IDE for meta-toolchain made with Yocto, for arm cortex A9 processor. After performing hello world test, which ran successfully, I created a basic program to test pthreads.
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <time.h>
#include <pthread.h>
#define MILLION 1000000 /* one million = 10^6*/
#define sec_to_nsec 1000000000 /* ns to s conversion = 10^9 */
#define FILENAME "Schd.txt"
#define FLUSH_TIME 10.0
#define SIG_LLP_TIMER SIGRTMIN+1
int isr_idx; /* counter of ISR occurred -- starts from 0 and increments at each interrupt*/
volatile float clk_k, /* MY_CLOCK() value for the current sample*/
clk_k_1; /* MY_CLOCK() value for the previous sample*/
/*clock and timer values*/
struct itimerspec custom_itimerspec;
timer_t timer_id;
clockid_t USED_CLK;
struct timespec tv;
float a_n;
/*THREAD DATA*/
pthread_t thread0;
pthread_attr_t attr;
struct sched_param param;
using namespace std;
void* thread_scheduler(){
//function pointer
//mainThread
//make thread for scheduling
//exit after max cycle
}
int main(void)
{
cout << "Starting the program!" << endl; /* prints Hello World */
cout<< "Creating a Thread to deploy" << endl;
int status;
param.__sched_priority = 99;
int retc;
/*PTHREAD ATTR setup*/
retc = pthread_attr_init(&attr);
retc |= pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
retc |= pthread_attr_setschedpolicy(&attr, SCHED_FIFO);
retc |= pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
retc |= pthread_attr_setschedparam(&attr,¶m);
if (retc != 0) {
//fail
while(1){}
}
retc = pthread_create(&thread0, &attr, (void * (*)(void *))thread_scheduler, NULL);
printf("Exiting here!");
return 0;
}
But I get this error, undefined reference to `pthread_create', followed with some make errors.
Though after doing some search I found that adding '-pthread' command in configure and autogen settings works for building the project, as described here. But I am puzzled why the compiler can't see these files even if this file is present in 'includes' in the drop down folder of project explorer.
The error about undefined reference is coming from linking step, not from compiling and assembling step, compile step would look for header files and its rightly finding the pthread.h from sysroot include directory as you see as well. After compiling, it has to invoke the linker to create the executable binary and thats where it fails.
When linking it need to add libpthread to linker commandline so linker can find the pthread_create function and link it into final executable, this is usually done via specifying LDFLAGS which then get appended to linker invocation.
compiler driver ( gcc ) can be used to drive both compiling and linking steps.
so when you add -pthread option to compiler and compiler is also used to perform linking then it translates this option into -lpthread to linker cmdline which would then find libpthread and link it in.
I had worked on RHEL 6.5 and developed some code which would use the function dirfd() for readdir_r(), like shown below:
#include <dirent.h>
#include <sys/types.h>
void some_function(){
DIR *dir = NULL;
struct dirent *pentry = NULL, *next_file = NULL;
if ((dir = opendir("/ZB_RQ/")) != NULL) {
len_pentry = offsetof(struct dirent, d_name) + fpathconf(dirfd(dir), _PC_NAME_MAX) + 1;
pentry = malloc(len_pentry);
if(!pentry){
exit(0);
}
for(;;){
readdir_r(dir, pentry, &next_file);
if(!next_file){
//No file to iterate.
break;
}
else{
// do something
}
}
}
}
This piece of codes work fine in RHEL 6.5 (Linux) but when I run this in Oracle Solaris 10, it fails with an error Undefined symbol dirfd.
I have searched this fucntion in /usr/include/dirent.h but it is not there. The same is available in dirent.h version of Linux.
I have read somewhere that dirfd() is not available in Solaris 9 and 10.
So, is there any equivalent workaround of this function in Solaris 10?
This late BSD function was standardized in 2008 while Solaris 9 was released in 2001 and Solaris 10 in 2005. That's the reason why it isn't available with these versions.
dirfd is available with the current version, Solaris 11.
For older ones, reimplementing dirfd seems to be obvious, given the fact the file descriptor is already in the passed structure, here dir->d_fd or dir->dd_fd depending on whether __XOPEN_OR_POSIX is defined or not.
I making a Localization project Using Arduino and Xbee Zg where i need to measure time in nano second resolution im using arduino due board with 84 Mhz clock and arduino 1.5.2 IDE
im trying to use clock_gettime function i already included time.h but i get the same
compiling error
clock_gettime
is not declared in this scope
this is just a part of my Distance_Measurement.c file
#include "Distance_Measurement.h"
#include "time.h"
struct timespec start, stop;
bool Start_Time()
{
if(clock_gettime(CLOCK_REALTIME,&start) == -1)
return false;
else
return true;
}
bool Stop_Time()
{
if(clock_gettime(CLOCK_REALTIME,&stop) == -1)
return false;
else
return true;
}
double Cal_Time_Nano()
{
return (stop_time.tv_nsec - start_time.tv_nsec);
}
please help me
i first used #include i got the same error i have found that visual studio have included anther time.h not time.h in arduino gcc so i copied the last one and pasted it to arduino libraries path with my distance measurement library – PrinceOfEgy
In Java you can do this:
long now = (new Date()).getTime();
How can I do the same but in C++?
Because C++0x is awesome
namespace sc = std::chrono;
auto time = sc::system_clock::now(); // get the current time
auto since_epoch = time.time_since_epoch(); // get the duration since epoch
// I don't know what system_clock returns
// I think it's uint64_t nanoseconds since epoch
// Either way this duration_cast will do the right thing
auto millis = sc::duration_cast<sc::milliseconds>(since_epoch);
long now = millis.count(); // just like java (new Date()).getTime();
This works with gcc 4.4+. Compile it with --std=c++0x. I don't know if VS2010 implements std::chrono yet.
There is no such method in standard C++ (in standard C++, there is only second-accuracy, not millisecond). You can do it in non-portable ways, but since you didn't specify I will assume that you want a portable solution. Your best bet, I would say, is the boost function microsec_clock::local_time().
I like to have a function called time_ms defined as such:
// Used to measure intervals and absolute times
typedef int64_t msec_t;
// Get current time in milliseconds from the Epoch (Unix)
// or the time the system started (Windows).
msec_t time_ms(void);
The implementation below should work in Windows as well as Unix-like systems.
#if defined(__WIN32__)
#include <windows.h>
msec_t time_ms(void)
{
return timeGetTime();
}
#else
#include <sys/time.h>
msec_t time_ms(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (msec_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
}
#endif
Note that the time returned by the Windows branch is milliseconds since the system started, while the time returned by the Unix branch is milliseconds since 1970. Thus, if you use this code, only rely on differences between times, not the absolute time itself.
You can try this code (get from StockFish chess engine source code (GPL)):
#include <iostream>
#include <stdio>
#if !defined(_WIN32) && !defined(_WIN64) // Linux - Unix
# include <sys/time.h>
typedef timeval sys_time_t;
inline void system_time(sys_time_t* t) {
gettimeofday(t, NULL);
}
inline long long time_to_msec(const sys_time_t& t) {
return t.tv_sec * 1000LL + t.tv_usec / 1000;
}
#else // Windows and MinGW
# include <sys/timeb.h>
typedef _timeb sys_time_t;
inline void system_time(sys_time_t* t) { _ftime(t); }
inline long long time_to_msec(const sys_time_t& t) {
return t.time * 1000LL + t.millitm;
}
#endif
int main() {
sys_time_t t;
system_time(&t);
long long currentTimeMs = time_to_msec(t);
std::cout << "currentTimeMs:" << currentTimeMs << std::endl;
getchar(); // wait for keyboard input
}
Standard C++ does not have a time function with subsecond precision.
However, almost every operating system does. So you have to write code that is OS-dependent.
Win32:
GetSystemTime()
GetSystemTimeAsFileTime()
Unix/POSIX:
gettimeofday()
clock_gettime()
Boost has a useful library for doing this:
http://www.boost.org/doc/libs/1_43_0/doc/html/date_time.html
ptime microsec_clock::local_time() or ptime second_clock::local_time()
Java:
package com.company;
public class Main {
public static void main(String[] args) {
System.out.println(System.currentTimeMillis());
}
}
c++:
#include <stdio.h>
#include <windows.h>
__int64 currentTimeMillis() {
FILETIME f;
GetSystemTimeAsFileTime(&f);
(long long)f.dwHighDateTime;
__int64 nano = ((__int64)f.dwHighDateTime << 32LL) + (__int64)f.dwLowDateTime;
return (nano - 116444736000000000LL) / 10000;
}
int main() {
printf("%lli\n ", currentTimeMillis());
return 0;
}