static variable's address can access by other files or not

Viewed 41

I have one question about the static variable in C language. For example, there are two files, one is "Action.c" and another is "Result.c"

[In Action.c File] `

static uint8_t actionResult[10] = {0x00};
void getActionResult (uint8_t** resultPtr)
{
    *resultPtr = actionResult;
}

[In Result.c]

void main (void)
{
    uint8_t* getResultPtr = NULL;
    getActionResult(&getResultPtr);
}

I want to know this is legal method to get value from "Action.c" file or not. And also want to know transfer static variable address to other file is bad idea or not?

Thank you so much.

1 Answers

Is it legal? Yes. A file-level static variable cannot be seen from outside a translation unit but, if that translation unit publishes the address somehow (as you have), it can be accessed or changed by dereferencing that address.

Is it a good idea? Not really. The whole point of file-level statics is to protect them from things outside the translation unit. If you're going to allow this, there's really no point in marking it static at all.

Just define it as uint8_t actionResult[10] = {0x00}; and have main use the variable name rather than getting and dereferencing its address.

Related