【问题标题】:C extern clock_t variables not working as expected in file; [duplicate]C extern clock_t 变量在文件中未按预期工作; [复制]
【发布时间】:2017-05-02 16:22:29
【问题描述】:

所以我有 3 个文件; main.c , file.c 文件.h

在 file.h 中我声明了 3 个变量

extern  clock_t start_t, end_t, total_t;

在file.c中我写了一个函数来保存主运行程序的时间长度; 在 file.h 中,我将其称为“void saveLog(void);”

void saveLog(void)
{   
end_t = clock();
total_t = (end_t - start_t);
double time_spent = (double) total_t / CLOCKS_PER_SEC;

double *arr = malloc(sizeof(double));
*arr = time_spent;

FILE* fp = fopen("log.txt","wb");
if (fp)
{
    printf("Elapsed: %f seconds\n", (double) time_spent);
    fwrite(arr, 1, sizeof(double), fp);
    fclose(fp);
}
}

在 main.c 开头的 main 我写了 start_t = clock(); 最后写了atexit(savelog) 我在所有文件中包含了所有库(time.h、stdlib.h、stdio.h)

编译时出现错误apple linker id error

Undefined symbols for architecture x86_64:
  "_end_t", referenced from:
      _saveLog in file.o
  "_start_t", referenced from:
      _check_answer in main.o
      _saveLog in file.o
  "_total_t", referenced from:
      _saveLog in file.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

顺便说一句,我的想法是,开始计算时钟和 main 的开始,并简单地在函数中进行数学运算。 我的问题是,为什么它不起作用?我还应该如何使用clock_t 变量?我尝试使用 int 进行一些测试,并且似乎可以很好地引用。

【问题讨论】:

  • 没有complete self-contained example 就不容易看出哪里出了问题。另外:将"b" 模式和fwrite() 与文本文件一起使用是不常见的。
  • 你有变量的声明,但没有定义。
  • 谢谢Barmar,我怎么看不到!

标签: c linker sharedpreferences clock atexit


【解决方案1】:

我发现我错过了什么;我忘记在包含main() 的文件中定义变量(尽管任何其他源文件都可以定义它们,只要只有一个文件定义它们并且在链接程序时链接该文件的目标代码)。

【讨论】:

    猜你喜欢
    • 2017-08-26
    • 2023-03-24
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 2019-05-18
    • 2020-11-30
    • 2012-02-29
    • 2012-06-18
    相关资源
    最近更新 更多