简体   繁体   中英

How to access local static variables and local variables inside a function from other files in C/C++ programming?

file1.c

int b=2;

void func(){
    int c=10;
    static int d=10;
    int *cp=&c;
}

main.c

#include <stdio.h>
#include <stdlib.h>
extern b;
extern *cp;

int main()
{
    int a=1;
    printf("a=%d\nb=%d\n",a,b);
    printf("c=%d\nd=%d\n",c,*cp);
    return 0;
}

I couldn't able to access local variable 'c' from other file using pointe '*cp' as well. I know by default we can access the functions from other files without using extern keyword but how to access the local variables and static variables present inside those functions ?

It is not possible. The variables in that function are scoped for use only in that function. However if you made variable c a static one, you could make a global pointer, declared in the same place as b . Then you could declare a extern int *ptr_to_c in main.c and be able to access the variable c through pointer access.

```c
file1.c

int b=2;

void func(){
// local scope, stored ok stack, can only be accessed in this function
    int c=10;
// stored in RAM, can only be accessed in this function
// but if you take a pointer to it, it will be valid after this function executes
    static int d=10;
// the pointer itself, cp is stored on stack and has local scope
    int *cp=&c;
}

main.c

#include <stdio.h>
#include <stdlib.h>
// this will allow you to access "b" in file1.c
// it should read: extern int b;
extern b;
// you will probably get link errors, this does not exist
extern *cp;

int main()
{
    int a=1;
    printf("a=%d\nb=%d\n",a,b);
    printf("c=%d\nd=%d\n",c,*cp);
    return 0;
}
```

You could do this:

file1.cpp

int * cp =0;
void func() {
  static int c;
  // store c's adress in cp
  cp = &c;
}

main.c

extern int *cp;
int main()
{
 // you need to call this otherwise cp is null
  func();
  *cp = 5;
}

However, this is very bad c code. You should simply declare int c with file scope in file1.c exactly like b.

In practice, if you think you need static variables inside a function you should stop and reconsider.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM