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

So, I am working on a “fast and dirty” profiler for firmware - I just need to know how long some functions take. Just printing the time it takes each time distorts the results, since logging is expensive, so I save a bunch of results to an array and dump them after a while.

When working in one compilation unit (one source file), I just had a lot of static arrays storing the results. Now I need to do this through several files. I could "copy paste" the code, but it would just be ugly ("Bear with me"). If I put the temporary code in a separate compilation unit, make static variables and provide access functions in the header file, every time I want to access these static variables, I will make overhead function calls.

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

I always tried to encapsulate the data, rather than using global variables, but this situation requires this simply because of speed issues.

Hope this makes sense! Thank!

EDIT: Okay, so I see what I ask is impossible: do you see alternatives that essentially allow me to directly access the data of another compilation unit?

EDIT2: Thanks for the answers of Pablo and Jonathan. I ended up accepting Pablo because I did not have a clear place to get a pointer to static data (like Jonathan) in my situation. Thanks again!

+3
source share
2 answers

No, it is not possible to access staticcompilation unit variables from another. staticThe keyword precisely prevents this.

If you need to access the global values ​​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

static , . , (I.E., ).

+7

C1 C2, C1 , C2, - .

, " " , , ; , .

; ( ) , .

, ; static , , static - , C. .

+3

Source: https://habr.com/ru/post/1785240/


All Articles