在C函数中声明extern变量?

Wan*_*uma 16 c declaration extern variable-declaration

我在C文件中定义了一个变量:int x我知道extern int x如果我想在其他文件中使用它,我应该用它来在其他文件中声明它.

我的问题是:我应该在其他文件中将其声明在哪里?

  1. 在所有功能之外,

    // in file a.c:
    int x;
    
    // in file b.c:
    extern int x;
    void foo() { printf("%d\n", x); }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在将使用它的功能内?

    // in file b.c:
    void foo() {
       extern int x;
       printf("%d\n", x);
    }
    
    Run Code Online (Sandbox Code Playgroud)

我的怀疑是:

  • 哪一个是正确的?或者
  • 如果两者都正确,哪个是首选?

Lid*_*Guo 15

  1. 两者都是正确的.

  2. 哪一个更受欢迎取决于变量的使用范围.

    • 如果只在一个函数中使用它,则在函数中声明它.

      void foo() 
      {
           extern int x;   <--only used in this function.
           printf("%d",x);   
      }
      
      Run Code Online (Sandbox Code Playgroud)
    • 如果它由文件中的多个函数使用,则将其声明为全局值.

      extern int x;   <-- used in more than one function in this file
      void foo()
      {
          printf("in func1 :%d",x);   
      }    
      void foo1() 
      {
          printf("in func2 :%d",x);   
      }  
      
      Run Code Online (Sandbox Code Playgroud)


Gri*_*han 5

假设你在函数内声明:

// in file b.c:
void foo() {
    extern int x;
    printf("%d\n", x);
}
void foo_2() {
    printf("%d\n", x);  <-- "can't use x here"
}
Run Code Online (Sandbox Code Playgroud)

然后x在函数内局部可见foo(),如果我有任何其他函数说foo_2(),我无法访问x内部foo_2().

然而,如果您x在所有函数之前声明外部,那么它将在完整文件(所有函数)中全局可见/可访问.

  // in file b.c:
  extern int x;
  void foo() { printf("%d\n", x); }
  void foo_2() { printf("%d\n", x); }  <--"visible here too"
Run Code Online (Sandbox Code Playgroud)

因此,如果您x只需要单个函数,那么您可以在该函数内部声明,但如果x在多个函数中使用,则x在所有函数外部声明(您的第一个建议).


Arm*_*gdy 5

您可以使用另一种技术来使用说明符extern声明变量.

// in file a.c:
int x;
Run Code Online (Sandbox Code Playgroud)
// in file b.h  //   make a header file and put it in 
                //   the same directory of your project and every
                //   time you want to declare this variable 
                //   you can just INCLUDE this header file as shown in b.c
extern int x;
Run Code Online (Sandbox Code Playgroud)
// in file b.c:
#include "b.h"
void foo() { printf("%d\n", x); }
Run Code Online (Sandbox Code Playgroud)