【问题标题】:what is the error in the below c program?以下c程序中的错误是什么?
【发布时间】:2014-05-14 10:55:44
【问题描述】:
a.c:
#include "a.h"
double GetTimeStamp()
{
            struct timespec start;

            if((clock_gettime( CLOCK_REALTIME, &start)) == -1 )
            {
              perror("clock gettime\n");

            }

/* I am calculating the Clock granularity here the granularity is basically how long that timer interrupt
 * will last while it's processing the background task.*/
            //micro seconds output
        return (1e3 * start.tv_sec + start.tv_nsec * 1e-3);

}

int a()
{
intr_rx_time = GetTimeStamp();
IPLatency = intr_rx_time;

}

a.h:
a();
double intr_rx_time, IPLatency;

b.c:
#include "a.h"
extern double IPLatency;
uint32 ipLatency;

int main()
{
  ipLatency = (uint32)IPLatency;
  printf("Current IP Latency microseconds: %ld\n", ipLatency);
}

在上面:我正在计算来自 a.c 程序的时间戳。稍后我正在读取 b.c 程序中的计算时间戳值,如上所示。但是我在 b.c 程序中将输出设为 0。上述程序中的错误是什么?有人可以帮忙吗?

【问题讨论】:

    标签: c linux timer timestamp qnx


    【解决方案1】:

    a.c 和 b.c 中的 intr_rx_timeIPLatency 是不同的对象。

    extern 添加到头文件(从“定义”更改为“声明”)并在单个.c 文件中定义变量(不带extern)。

    // a.h
    int a(void);
    extern double intr_rx_time, IPLatency;
    

    // a.c
    #include <stdio.h>
    #include <time.h>
    #include "a.h"
    double GetTimeStamp(void)
    {
        struct timespec start;
        if ((clock_gettime(CLOCK_REALTIME, &start)) == -1) {
            perror("clock gettime");
        }
        /* I am calculating the Clock granularity here the granularity is basically how long that timer interrupt
         * will last while it's processing the background task. */
        //micro seconds output
        return (1e3 * start.tv_sec + start.tv_nsec * 1e-3);
    }
    
    int a(void)
    {
        intr_rx_time = GetTimeStamp();
        IPLatency = intr_rx_time;
    }
    

    // b.c
    #include <inttypes.h>
    #include <stdio.h>
    #include "a.h"
    double IPLatency;
    uint32 ipLatency;
    
    int main(void)
    {
        ipLatency = IPLatency;
        printf("Current IP Latency microseconds: %" PRIu32 "\n", ipLatency);
    }
    

    【讨论】:

    • 你能帮我修改一下吗!!我不明白!
    • 请注意,您的 main() 函数不会从“a.c”调用任何函数
    • 警告:格式 '%u' 需要类型 'unsigned int',但参数 2 的类型为 'uint32'
    • @user3635707:你的编译器很有帮助。你有一个很好的编译器。警告意味着使用说明符 "%u" 打印 uint_32 类型的值是错误的:要么更改说明符,要么更改变量的类型(或强制转换,呃)。
    • 我使用了上面的代码,但它显示出指定的衰减
    【解决方案2】:

    1) 将 double intr_rx_time, IPLatency; 从 a.h 移动到 a.c

    2) a.h 中的原型

    a();
    

    应该是

    int a(void);
    

    3) 将以下行添加到 a.h

    #include<time.h> 
    #include<stdio.h>
    typedef unsigned int uint32;
    

    4) 在 b.c 中将 %ld 更改为 %d

    【讨论】:

    • 只有这样的变化?
    • 乍一看我发现,如果您仍然面临问题,为什么不能尝试更改和更新。
    • 我修改了:ipLatency = (uint32) IPLatency;我在 printf 中指定了 %ld。如果我指定 %d 那么它将显示警告。
    猜你喜欢
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 2023-03-08
    • 1970-01-01
    • 2013-02-16
    相关资源
    最近更新 更多