Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a static variable of one compilation unit from others directly, in C

So I'm working on a "quick and dirty" profiler for firmware- I just need to know how long some functions take. Merely printing the time it takes every time will skew the results, as logging is expensive- so I am saving a bunch of results to an array and dumping that after some time.

When working in one compilation unit (one source file), I just had a bunch of static arrays storing the results. Now I need to do this across several files. I could "copy paste" the code, but that would be just ugly (Bear with me). If I put timing code in a seperate compilation unit, make static variables, and provide accessor functions in the header file, I will be incurring the overhead of function calls every time i want to access those static variables.

Is it possible to access static variables of a compilation unit directly?

I've always tried to encapsulate data, and not use global variables, but this situation calls for it simply due to speed concerns.

I hope this makes sense! Thank you!

EDIT: Alright, so it appears what I'm asking is impossible- do any of you see alternatives that essentially allow me to directly access data of another compilation unit?

EDIT2: Thank you for the answers Pablo and Jonathan. I ended up accepting Pablo's because I didn't have clear place to get the pointer to the static data (as per Jonathan) in my situation. Thanks again!

like image 569
Alexander Kondratskiy Avatar asked Dec 22 '22 19:12

Alexander Kondratskiy


1 Answers

No, it's not possible to access static variables of a compilation unit from another one. static keyword precisely prevents that from happening.

If you need to access globals of one compilation unit from another, you can do:

file1.c:

int var_from_file1 = 10;

file2.c:

extern int var_from_file1;
// you can access var_from_file1 here

If you can remove the static keyword from your declarations, you should be fine. I understand that changing existing source code is not always an option (I.E. dealing with existing legacy compiled code).

like image 127
Pablo Santa Cruz Avatar answered Mar 02 '23 00:03

Pablo Santa Cruz