0

Several lines of code are worth a thousand words:

I have three simple files: header.h, main.cpp, other.cpp

// header.h

  #pragma once

inline const int& GetConst()
{
    static int n = 0;
    return n;
}

const int& r = GetConst();

// main.cpp

  #include "header.h"

int main()
{
    return 0;
}

// other.cpp

  #include "header.h"

When compiling the simplest project, the VC++ 2010 complains as follows:

ClCompile:
  other.cpp
  main.cpp
  Generating Code...
  other.obj : error LNK2005: "int const & const r" (?r@@3ABHB) already defined in main.obj
D:\Test\Debug\bug.exe : fatal error LNK1169: one or more multiply defined symbols found

Build FAILED.

Time Elapsed 00:00:00.29
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

I am sure this is a bug of VC++ 2010, because of the following two references:

1, The C++ standard says: (at page 140 of n3126)

"Objects declared const and not explicitly declared extern have internal linkage."

2, The MSDN says: (at: http://msdn.microsoft.com/en-us/library/357syhfh(VS.80).aspx)

"In C, constant values default to external linkage, so they can appear only in source files. In C++, constant values default to internal linkage, which allows them to appear in header files.

The const keyword can also be used in pointer declarations."

JoeG
  • 12,994
  • 1
  • 38
  • 63
xmllmx
  • 39,765
  • 26
  • 162
  • 323
  • 1
    possible duplicate of [Is this a BUG of VC++ 2010? About declaring a constant object in a header.](http://stackoverflow.com/questions/4185275/is-this-a-bug-of-vc-2010-about-declaring-a-constant-object-in-a-header) – Steve Townsend Nov 15 '10 at 15:29
  • 1
    Don't define variables in your header file (`r` in this case). This is nothing to do with constness. See dup question for fix. – Steve Townsend Nov 15 '10 at 15:30
  • 7
    I love how you assume this is a bug in a compiler used by millions, and couldn't be bothered to think it's a bug in your understanding of C++. – John Dibling Nov 15 '10 at 15:34

1 Answers1

10

The paragraph you cite from the C++ Standard reads (C++03 7.1.1/6):

Objects declared const and not explicitly declared extern have internal linkage.

You have not declared an object. You have declared a reference. A reference is not an object. That said, 3.5/3 says:

A name having namespace scope has internal linkage if it is the name of an object or reference that is explicitly declared const and neither explicitly declared extern nor previously declared to have external linkage

However, 8.3.2/1 says:

Cv-qualified references are ill-formed

So, while a const-qualified reference would have internal linkage, it's not possible to const-qualify a reference.

The reference in your sample program is not const-qualified, it's a reference to a const-qualified int.

James McNellis
  • 348,265
  • 75
  • 913
  • 977