0

c++ beginner here. I have a program with lots of globals shared across many .cpp source files (I've been given this to refactor from a single huge file, and need to do so quickly, rather than make it best practices). My idea is to write a header file that uses extern to declare all these globals, which I include wherever needed, and then have a .cpp file where they are all initialised. e.g.

extern int a;

in the header file and

int a = 1;

in the .cpp file.

This generally seems to work, except for anything using const. In this case the variables initialised in the .cpp do not end up in the symbol table when compiled (i.e. I can't find the variable when grepping through for it in the .o file), and I get a linking error saying undefined reference to variable. Why is this? Is it a language thing, or a compiler thing? (I was given a pretty sizeable makefile which I'm unfortunately not able to fully understand)

funklute
  • 581
  • 4
  • 21
  • @PaulR I'm not positive either, but the *"I get a linking error saying undefined reference to variable"* tipped me off that it is likely the same issue. – Cory Kramer Jun 05 '14 at 12:27
  • 1
    In this case, const implies internal linkage in C++, which is likely why it's not shown in your object symbol tables. – nos Jun 05 '14 at 12:28
  • 1
    Are you remembering to declare the variables `const` in the .cpp file as well? I use `extern const` all the time in this kind of situation without problem. – Matt Phillips Jun 05 '14 at 12:29

0 Answers0