I\'m new to C. I have a book in front of me that explains C\'s \"file scope\", including sample code. But the code only declares and initializes a file scoped variable - it
This is caused by confusing terms. file scope
in C does not refer to restrict linkage of an identifier to only one translation unit. It also doesn't mean that scope is limited to one physical file. Instead, file scope
means that your identifier is global. The term file
, here, refers to the text that results from processing all #include
, #define
and other pre-processor directives.
In general, scope is only a concept taking effect within one translation unit. When multiple compilations are involved, linkage starts to happen.
If you declare your file scope variable static
, then it gives the variable internal linkage, which means that it isn't visible outside of that translation unit.
If you don't declare it static explicitly, or if you declare the file scope variable extern
, then it is visible to other translation units: Those, if they declare a file-scope variable with the same identifier, will have that identifier link to that same variable.
In your case, the inclusion of bar.c
into foo.c
inserts the definition of fileScopeVariable
into the translation unit being compiled. Thus, it's visible in that unit.