C / C ++ scope in two different .cpp files

I would like to know why you cannot declare a global name with the same name in two different .cpp files. My understanding is considering scope, that it should be visible only to this particular .cpp file and not somewhere else, but it’s clearly complaining. The reason I do this is because the code is common and that is. any ideas?

Edit for clarity.

a.cpp

int g_x;

b.cpp

int g_x;

+5
source share
6 answers

So that the global variable (or function) is visible only to the file in which it was declared,

  • declare it staticor
  • (, ++) . , - , , , , .

( static ), ​​ - , extern.

, . , . static , , " ".

+7

:
, .. .
2 , ODR ( ).

(ODR), , , , - , , .


:
, ODR. :

static / .


:
/
Speaking Standardese:


Standerdese:
++ 11 3.2 [basic.def.odr]:

, , , .

3:

- , odr- ; . , ( ), (. 12.1, 12.4 12.8). , .

++ 11 7.3.1.1. [namespace.unnamed]

1/ -namespace ,

inlineoptnamespace unique { /* empty body */ }    
using namespace unique ;      
namespace unique { namespace-body }       

, , , .94

: ++ 03 static , ++ 11.

+5

, , , ( ).

, .

, , :

namespace {
    int my_global_variable;
}

. , "gorblegorble123". , :

using namespace gorblegorble123;    // As if this is present.

, .

. , .


, static , .

++ 98 ++ 03, ++ 11.

static - , , .

+3

static (C ++):

static int myGlobalVariable;

( ++):

namespace {
    int myGlobalVariable;
}
+2

why you can not declare a global with the same name in 2 different .cpp files

, , . , , .

( , ++ 03), , - :

file1.cpp

namespace
{
  int n;
};

file2.cpp

namespace
{
  int n;
};

.

+1

"c", 5 . C " ".

C (C99 , C1x) . ( 6.9.2).

1 . 144 , / . extern (i3) .

, , , extern, .

, C

int i3;

tupe int, , . int abc; char abc , ; , .

H & S5 , ​​, . .

, Alok.

+1

All Articles