Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between scope and linkage?

Tags:

c

scope

linkage

I tried different websites but I don't get it. Could you explain it in simple english?

like image 812
user3646717 Avatar asked Oct 27 '14 01:10

user3646717


2 Answers

"scope" is a namespace of the compiler; "linkage" is about compiled units.

I explain a bit more: A variable declared in a function has the scope of that function, i.e. it is visible only within that function. A variable declared as static in a source file, can be seen only by the code in that source file (and all included files!). Variables can also have global scope: they can be referred to in a source file, but not declared (allocated) in that source file but declared in another source file.

In stead of "source file" we should say "compilation unit" as it is the C source file being compiled, plus all included files. Scope refers to everything the compiler can "see" in a compilation unit. These are namespaces.

After compilation of a project there are a number of object files, one for each compile unit. Each may refer to variables used that are not declared in the compile unit. The linker must now resolve these references between object files: linkage.

This also holds for functions.

like image 154
Paul Ogilvie Avatar answered Nov 02 '22 04:11

Paul Ogilvie


Keep reading on your page (http://msdn.microsoft.com/en-us/library/teta4z44.aspx). This is talking about visibility of objects between translation units (source files). It first talks about "internal linkage": objects defined as static, unique to the translation unit but available throughout.

Next it talks about "external linkage": a like-level object not declared static. These are shared between translation units.

Finally, "no linkage": an object such as a variable within a function, not declared extern, which is unique to that scope.

If you follow the links on the bottom of the page, it's all explained.

like image 28
DoxyLover Avatar answered Nov 02 '22 05:11

DoxyLover