1

Let's say there is static variable static uint8 Data_updated_u8 in file first.c, and in some cyclic function its value is updating. Now I want the get the updated value of Data_updated_u8 in second.c file. Is there any way to get static variable in second.c without using extern variable? Or using pointers?

2
  • Yes, write an accessor/get API in the first file.
    – kaylum
    Aug 9, 2021 at 2:09
  • You'd use a function to access it, as others have said. But you should probably think a bit more on what you're doing in the first place. The function has to be global, so why not make the variable global? In either case you're suffering the downside of global variables, but with the way you're doing it you also suffer pointless extra cruft. Aug 9, 2021 at 2:49

1 Answer 1

4

Now I want the get the updated value of Data_updated_u8 in second.c file

This is a design problem. If you have a local static variable declared at file scope in a .c file, then that variable is to be regarded as private. If your design is sound, other files should not need direct access to that variable. So this is where you should step back and consider your program design before anything else.

Or using pointers?

Bad idea, that's even worse than using global variables. You shouldn't expose private variables through pointers. Nor should you use global variables. Overall, you shouldn't design in tight coupling between several files by creating strange dependencies like this.

If you actually need to share this variable with other files, then the correct way is to write a setter/getter API function which you provide through the header file. Then set/get the data by value. (You might not even need to set it from the outside?)

Additionally, don't invent some local garage standard uint8. Use the international C language standard uint8_t from stdint.h.

data.h

#include <stdint.h>

uint8_t get_data (void);

void set_data (uint8_t val);

data.c

#include "data.h"

static uint8_t data;

uint8_t get_data (void) { return data; }

void set_data (uint8_t val) { data = val; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.