Scope regions in C and C++
Many programmers have difficulty distinguishing the concepts of scope, storage allocation, and linkage. Dan begins the process of sorting them out.
Like many other programming languages, C employs concepts such as scope and storage allocation. The C standard also employs the lesser known concept of linkage. Some other programming languages employ this concept as well, but few aside from C++ use the same terminology as C.
Although most programmers understand scope and storage allocation well enough to cope with common programming situations, their understanding often breaks down when confronted with anything out of the ordinary. They also seem to have a sense of what linkage is, but don't really understand how it's distinct from the other concepts.
Much of the confusion stems from the complex semantics of storage class specifiers such as extern and static. The keyword static is particularly inscrutable. Sometimes it affects the way a program allocates storage. It can also affect how the linker resolves names as it links object files together. In C++, it can even restrict the behavior of class member functions. Understanding these distinctions can help you implement your designs more effectively and avoid some maintenance headaches.
In this installment, I'll explain how the C standard defines the concept of scope. The C++ standard describes scope much as the C standard does, but with a few noteworthy differences. I'll focus initially on what the C standard says and point out the differences with C++ as appropriate. I'll try to be reasonably precise without swamping you with unnecessary details.
As you well know, a C program can consist of numerous source files. A compiler processes one source file at a time. A source file usually contains #include directives that refer to headers. The compiler's preprocessor merges those headers with the source file to produce a transitory source file, which the standard calls a translation unit. Translation units are also known as compilation units.
Later phases of the compilation process transform each translation unit into an object file or object module. The linker combines object files and library components to produce an executable program.
As you'll see, you can't talk knowledgeably about scope and linkage without mentioning translation units.