1

So I'm having an issue with declaring a global variable (in the header) and using it. I've done some reading on header files and how they work, but I can't understand why my code isn't working.

Here's what I have (in a simplified manner):

Main:

// main.cpp

#include "source.hpp"

int main()
{
    return variable;
}

Source:

// source.cpp

#include "source.hpp"

variable = 17;

Header:

// source.hpp

#ifndef __SOURCE_HPP_INCLUDED__
#define __SOURCE_HPP_INCLUDED__

extern int variable;

#endif  // __SOURCE_HPP_INCLUDED__

I've tried with and without extern in the header file. I get this error when I try to (compile in the source): 'variable' does not name a type What am I not understanding properly?

Also, when I declare the same variable in main.cpp, the compiler does throw back an error about 'redefining' the variable. Why is that?

Max Jacob
  • 701
  • 1
  • 9
  • 20
  • 2
    Names that contain two consecutive underscores (`__SOURCE_HPP_INCLUDED__`) and names that start with an underscore followed by a capital letter are reserved to the implementation. Don't use them. – Pete Becker Jan 25 '16 at 01:28
  • Possible duplicate of [What is an undefined reference/unresolved external symbol error and how do I fix it?](http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – IInspectable Jan 25 '16 at 01:33

1 Answers1

3

In source.cpp you need to define the variable:

int variable = 17;
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • That solved it! So is true that I always need to re-define the variable somewhere else (such as the source), even though I already defined it in the header? – Max Jacob Jan 25 '16 at 01:40
  • 3
    @MaxJacob: `extern int i;` is a **declaration**, `int i;` is a definition. C++ has a single-definition rule. You cannot define a symbol more than once. – IInspectable Jan 25 '16 at 01:43
  • That makes more sense. Thank you for the clarification! – Max Jacob Jan 25 '16 at 01:46