Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can anyone explain this portion of the C++0x draft standard?

Tags:

c++

c++11

linkage

From ISO Standard Draft: §3.0/9:

n3234 says:

A name used in more than one translation unit can potentially refer to the same entity in these translationunits depending on the linkage (3.5) of the name specified in each translation unit.

Can anyone explain this point with an example, please?

What is that statement actually saying? Can any one prove this point in terms of a program?

like image 486
1User Avatar asked Nov 16 '25 05:11

1User


1 Answers

Sure! What this is saying is that if you have multiple source files (translation units) that both use some name (for example, the name of a variable, class or function), then it's possible that those different files are talking about the same variable, class, or function, assuming that that entity was declared in a way that makes it visible across different files (that is, depending on its linkage).

For example, if I have this file:

A.cpp:

int globalInt;

int main() {
     globalInt = 137;
}

And this one here:

B.cpp:

extern int globalInt;

void foo() {
    globalInt = 42;
}

Then in both files, the name globalInt refers to the global int variable globalInt defined in A.cpp. That's all that this point is saying.

Note, however, that if I declare globalInt without external linkage, then the two files will be talking about different variables. For example, in this case:

C.cpp:

static int globalInt;

int main() {
     globalInt = 137;
}

D.cpp:

static int globalInt;

void foo() {
    globalInt = 42;
}

Now the globalInt variable referenced in C.cpp is not the same as the one in D.cpp, even though they have the same name.

Hope this helps!

like image 191
templatetypedef Avatar answered Nov 18 '25 20:11

templatetypedef