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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I've solved it by adding "extern" to the definition as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.