C extern clock_t variables not working as expected in file;

244 views Asked by At

So I have, 3 files; main.c , file.c file.h

in file.h I declared 3 variables

extern  clock_t start_t, end_t, total_t;

in file.c I wrote a function to save the length of time of main running program; and in file.h I reference it as "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);
}
}

in main.c at the start of main I wrote start_t = clock(); and at the end wrote atexit(savelog) I included all libraries (time.h , stdlib.h , stdio.h in all files)

When compiling I get the error 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)

By the way my thinking is , to begin counting clock and the start of main and simply do the math in the function. My question is ,why does it not work? How else should I use the clock_t variables? I tried some testing with int's and the seemed to be referenced just fine.

1

There are 1 answers

0
Arn as On

I found out what I was missing; I forgot to define the variables in the file that contains main() (though any other source file could define them instead, as long as only one file defines them and the object code for that file is linked when the program is linked).