How to share a variable among multiple files in C language.

To share a variable among multiple files, you can utilize external variables or global variables.

The method of using external variables is as follows:

  1. external
  2. external

The example code is as follows:

The first file, file1.c:

int sharedVariable = 10;

The second file is file2.c.

extern int sharedVariable;

int main() {
    // 使用共用变量
    printf("%d\n", sharedVariable);
    return 0;
}

The method of using global variables is as follows:

  1. fixed
  2. external

The example code is shown below:

The file named file1.c:

static int sharedVariable = 10;

The second file is file2.c.

extern int sharedVariable;

int main() {
    // 使用共用变量
    printf("%d\n", sharedVariable);
    return 0;
}

All of the methods mentioned require compiling multiple files together at compile time, for example, using the following command to compile the files:

gcc -o program file1.c file2.c
bannerAds