Global const object shared between compilation units

Viewed 2812

When I declared and initialized a const object.

// ConstClass.h
class ConstClass
{
};

const ConstClass g_Const;

And two cpp files include this header.

// Unit1.cpp
#include "ConstClass.h"
#include "stdio.h"

void PrintInUnit1( )
{
    printf( "g_Const in Unit1 is %d.\r\n", &g_Const );
}

and

// Unit2.cpp
#include "ConstClass.h"
#include "stdio.h"

void PrintInUnit2( )
{
    printf( "g_Const in Unit2 is %d.\r\n", &g_Const );
}

When i build the solution, there was no link error, what you will get If g_Const is a non-const fundamental type!

And PrintInUnit1() and PrintInUnit2() show that there are two independent "g_Const"s with different address in two compilation units, Why?

==============

I know how to fix it.(use extern keyword to declaration, and define it in one cpp file.)

I wonder to know why I did't get redfined link error in this sample.

2 Answers
Related