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 關鍵字的情況下從其他檔案訪問函式,但是如何訪問這些函式中存在的區域變數和靜態變數?
uj5u.com熱心網友回復:
這不可能。該函式中的變數僅限于在該函式中使用。但是,如果將變數c設為靜態變數,則可以創建一個全域指標,在與b. 然后你可以宣告一個extern int *ptr_to_cinmain.c并且能夠c通過指標訪問來訪問變數。
uj5u.com熱心網友回復:
```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在函式內部使用變數,你應該停下來重新考慮。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/365029.html
