3

In A.h:

#ifndef A_h
#define A_h

#include "string"

extern std::string a;

#endif

In A.cpp, in the global scope:

#include "A.h"

std::string a = "a";
Hobbyist
  • 885
  • 2
  • 10
  • 23

2 Answers2

3

You are not redefining a variable, because your code has only one definition - the one in the CPP file. The one in the header is a declaration, because it uses an extern keyword. The CPP file provides a definition to the variable declared in the header.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • I'm unclear about why you need to declare the type of the variable in the global scope where as you would only need to declare a variable's name to assign to it in a function, can you enlighten me? – Hobbyist Aug 11 '13 at 13:08
  • @Hobbyist Without the type the variable would not be usable outside of the CPP file where the variable is defined: compiler needs to know the type of `a` in order to let you call its member functions, e.g. `a.size()` or `a.c_str()`. – Sergey Kalinichenko Aug 11 '13 at 13:10
  • Thanks, having both the type and name looked like a redeclaration to me which confused me. – Hobbyist Aug 11 '13 at 13:15
  • @Hobbyist You can declare the same thing as many times as you wish, as long as all declarations are consistent with each other. In fact, in C++ a definition is not only a definition, but a combined definition/declaration. It is defining that should generally be done only once to avoid linking errors. – Sergey Kalinichenko Aug 11 '13 at 13:17
1

Think of it this way: The compiler sees A.cpp once, and only once. If your project has many source files that #included A.h, the compiler would see A.h multiple times, once for each #include, as it processes all the *.cpp files. It is logical in that scenario that there be one definition, and multiple declarations

What you have is correct - a variable in global scope in A.cpp. Being global and non-static, it has the potential to be used elsewhere. In fact it is polluting the namespace if it is not used elsewhere.

Paul Beckingham
  • 14,495
  • 5
  • 33
  • 67