ivarec
ivarec

Reputation: 2612

Undefined reference issue with a minimal "extern" usage test case

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

Upvotes: 2

Views: 186

Answers (1)

Dawid
Dawid

Reputation: 643

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.

Upvotes: 2

Related Questions