What is the difference between “File scope” and “program scope”

坚强是说给别人听的谎言 提交于 2019-12-02 18:12:33

In C99, there's nothing called "program scope". In your example variable x has a file scope which terminates at the end of translation unit. Variables y and z which are declared static also have the file scope but with internal linkage.

C99 (6.2.2/3) If the declaration of a file scope identifier for an object or a function contains the storage class specifier static, the identifier has internal linkage

Also, the variable x has an external linkage which means the name x can is accessible to other translation units or throughout the program.

C99 (6.2.2/5) If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.

Variables declared as static cannot be directly accessed from other files. On the contrary, non-static ones can be accessed from other files if declared as extern in those other files.

Example:

foo.c

int foodata;
static int foodata_private;

void foo()
{
    foodata = 1;
    foodata_private = 2;
}

foo.h

void foo();

main.c

#include "foo.h"
#include <stdio.h>

int main()
{
    extern int foodata; /* OK */
    extern int foodata_private; /* error, won't compile */

    foo();

    printf("%d\n", foodata); /* OK */

    return 0;
}

Generally, one should avoid global variables. However, in real-world applications those are often useful. It is common to move the extern int foo; declarations to a shared header file (foo.h in the example).

C programs can be written in several files, which are combined by a linker into the final execution. If your entire program is in one file, then there is no difference. But in real-world complex software which includes the use of libraries of functions in distinct files, the difference is significant.

A variable with file scope is only visible from its declaration point to the end of the file. A file refers to the program file that contains the source code. There can be more than one program files within a large program. Variables with program scope is visible within all files (not only in the file in which it is defined), functions, and other blocks in the entire program. For further info. check this : Scope and Storage Classes in C.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!