Rajat
Rajat

Reputation: 487

Internal linkage for const in C++, yet I get duplicate symbols

Could someone please advise?

If const in C++ defaults to internal linkage, why do I get multiple definition errors in the code below?

First, the file dem.h:

#ifndef _DEM_H_
    #define _DEM_H_
    class Dem {
        public:
            static const int i;
    };

    const int Dem::i = 10;
#endif

Them imp1.cpp:

#include "dem.h"
#include <iostream>

using namespace std;
extern int foo();

int main() {
        cout << foo() << endl;
}

and imp2.cpp:

#include "dem.h"

int foo() {
    return Dem::i ;
}

I compile with the following command and results:

$ g++ imp1.cpp imp2.cpp
/tmp/ccmGt0OY.o:imp2.cpp:(.rdata+0x0): multiple definition of `Dem::i'
/tmp/cc5sN7dz.o:imp1.cpp:(.rdata+0x0): first defined here
collect2: ld returned 1 exit status

Upvotes: 1

Views: 408

Answers (2)

ds1848
ds1848

Reputation: 172

Its static to the compilation unit. You are compiling in two steps - first impl1.cpp and then impl2.cpp - and in each unit the compiler instantiates the static data member. When the linker then tries to link the two associated object files together, it sees two different definitions for the same symbol , and so you get a multiple definition error.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881373

From C++11 [basic.link], paragraph 5:

In addition, a member function, static data member, a named class or enumeration of class scope, or an unnamed class or enumeration defined in a class-scope typedef declaration such that the class or enumeration has the typedef name for linkage purposes (7.1.3), has external linkage if the name of the class has external linkage.

Because your class has external linkage, so does your static data member.

Upvotes: 3

Related Questions