-->

What does external linkage mean [duplicate]

2019-08-22 07:15发布

问题:

This question already has an answer here:

  • What is an undefined reference/unresolved external symbol error and how do I fix it? 33 answers

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:

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);