-2

Consider the following a.cpp and b.cpp files:

ebra@him:/tmp$ cat a.cpp 
const int i = 5;

ebra@him:/tmp$ cat b.cpp 
int main()
{
  extern int i;
  return i;
}

ebra@him:/tmp$ g++ *.cpp
/tmp/ccqBWi4e.o: In function `main':
b.cpp:(.text+0x6): undefined reference to `i'
collect2: error: ld returned 1 exit status

The question is how I can use the i variable that is declared in a.cpp file inside b.cpp?

Note that

  1. I added the keyword const inside b.cpp too, but nothing changed.
  2. I have the same problem with static and static const variables too!
Ebrahim Ghasemi
  • 5,850
  • 10
  • 52
  • 113
  • 2
    static are always local to a file. Why did you declare `extern int i` inside `main`? it should have been declared outside. – Matthieu Brucher Dec 17 '18 at 11:37
  • @fionbio it is absolutely not necessary to use includes to refer to an entity declared in one source file from another. The issue here is linkage. – davmac Dec 17 '18 at 11:39
  • Add this line to the very beginning of a.cpp: `extern const int i;` – Eljay Dec 17 '18 at 12:43

2 Answers2

4

In C++, when you declare a variable to be const at namespace scope it automatically has internal linkage. Adding static will also yield in internal linkage with or without const

Therefore they are not available outside the translation unit, hence the linker error.

P0W
  • 46,614
  • 9
  • 72
  • 119
0

Put it in a header file, that way they both have the same value (different variables, same name, same value).

I think you can also override to make it external linkage, but this will get you nothing: no behaviour changes; No efficiency improvement, for int.

ctrl-alt-delor
  • 7,506
  • 5
  • 40
  • 52