0

Consider the following code:

#include <stdio.h>

namespace EnclosingNmspc
{
    namespace Nmspc
    {
        extern int a;//This a and the a defined above denote the same entity
        int a=5;
    }
}

extern int a;

int main()
{ 
    printf("%d\n",a);
}

There is the quote from 3.5/2:

When a name has external linkage , the entity it denotes can be referred to by names from scopes of other translation units or from other scopes of the same translation unit.

I dont understand why this rule doesn't work in my case? I have undefined reference linker error.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
St.Antario
  • 26,175
  • 41
  • 130
  • 318

1 Answers1

0

Your question is already answered there canonically.

You've been missing to have a definition for ::a in a different compilation unit.

int a=5; actually defines extern int a; in the same scope. But that's not accessed with

printf("%d\n",a);

in your main program. To check for the stuff from your namespace try

printf("%d\n",EnclosingNmspc::Nmspc::a);
Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • But the spec said that _the entity it denotes can be referred to by names from scopes of other translation units or `from other scopes of the same translation unit`._ – St.Antario May 24 '14 at 14:31
  • @St.Antario you still have to provide a definition, the compiler doesn't do it for you automatically. – Captain Obvlious May 24 '14 at 14:36
  • It's either declare `extern int a;` and have the definition elsewhere, **or** define `int a;` and have it accessible from elsewhere through an `extern` declaration. If you want to hide `a` from external linkage put it in an unnamed namespace. – πάντα ῥεῖ May 24 '14 at 14:37
  • Note that there is no shadowing (see 3.3.10/1). Declaration extern int a and definition int a=5 denote the same entity (see 3.3.1/4). – St.Antario May 24 '14 at 14:41
  • What should be the point of using `extern` there then?? – πάντα ῥεῖ May 24 '14 at 14:43
  • @St.Antario Look at `extern` like a forward declaration. `void f();` and `void f() {}` denote the same entity too. – Captain Obvlious May 24 '14 at 14:46
  • The point is to understand what does quote in my start post mean? I'm trying to do an example that explain how does external linkage works for names located in the same translation unit. – St.Antario May 24 '14 at 14:47
  • @CaptainObvlious It is not depends on extern specifier. I don't understand what you tried to say in your comment? – St.Antario May 24 '14 at 14:49