[英]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;
}
我也無法使用指針 '*cp' 從其他文件訪問局部變量 'c'。 我知道默認情況下我們可以在不使用 extern 關鍵字的情況下從其他文件訪問函數,但是如何訪問這些函數中存在的局部變量和靜態變量?
這不可能。 該函數中的變量僅限於在該函數中使用。 但是,如果將變量c
設為靜態變量,則可以創建一個全局指針,在與b
相同的位置聲明。 然后你可以在main.c
聲明一個extern int *ptr_to_c
並且能夠通過指針訪問來訪問變量c
。
```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;
}
```
你可以這樣做:
文件1.cpp
int * cp =0;
void func() {
static int c;
// store c's adress in cp
cp = &c;
}
主文件
extern int *cp;
int main()
{
// you need to call this otherwise cp is null
func();
*cp = 5;
}
但是,這是非常糟糕的c 代碼。 您應該像 b 一樣簡單地在 file1.c 中聲明具有文件作用域的 int c。
在實踐中,如果你認為你需要在函數中使用static
變量,你應該停下來重新考慮。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.