2

My test case has two files:

a.cc:

#include <iostream>

using namespace std;

const string program_name("myprog");

b.cc:

#include <iostream>

using namespace std;

extern const string program_name;

int main(int argc, char **argv) {
    cout << program_name << endl;

    return 0;
}

When compiling, I'm getting the following output:

$ g++ -c a.cc -o a.o -std=c++11 -O2
$ g++ -c b.cc -o b.o -std=c++11 -O2
$ g++ a.o b.o -o case
b.o: In function `main':
b.cc:(.text.startup+0x7): undefined reference to `program_name'
collect2: error: ld returned 1 exit status

In a.o, I have the following symbol:

0000000000000018 b _ZL12program_name

And in b.o:

         U program_name

The question is: why I'm shooting myself in the foot here?

Note: g++ 4.9.1

Lkopo
  • 4,798
  • 8
  • 35
  • 60
ivarec
  • 2,542
  • 2
  • 34
  • 57

1 Answers1

2

Good one. It's all due to const keyword.

It's already on stackoverflow: [click]

Let me quote:

It's because const implies internal linkage by default, so your "definition" isn't visible outside of the translation unit where it appears.

Community
  • 1
  • 1
Dawid
  • 623
  • 3
  • 9