Static and Namespace

When I try to compile program, in which I have additional classes and one header file for globals, I always get an error LNK2005 which says that I have already defined a value
1
2
3
4
5
6
7
8
9
10
#pragma once

const int WIDTH = 800;
const int HEIGHT = 600;

bool Start_Game = true; // 1
bool Render = false; // 2
bool keys[6] = { false, false, false, false, false, false }; // 3

enum KEYS { W, A, S, D, SPACE, ESCAPE };

The only variables that give error are marked with 1,2,3. Now, I tried using static and it didn't give me any error. I also tried using unnamed namespace, and it also didn't give me any error. Can anyone explain me these two, what is the difference, how do they work, and which one to use?
Move those lines to a .cpp file, and replace them in that header with
1
2
3
extern bool Start_Game;
extern bool Render;
extern bool keys[6]; //Not entirely sure about this one 


Using static or an anonymous namespace will create separate variables with those names in each translation unit that includes that header, meaning that if you change the value of a variable in one file, the change will only be visible to functions defined in that file. For example,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//foo.h
static int a = 42;
void f();

//bar.cpp
#include "foo.h"

void f(){
    a *= a;
}

//baz.cpp
#include <iostream>
#include "foo.h"

int main(){
    std::cout <<a<<std::endl;
    f();
    std::cout <<a<<std::endl;
}
Output:
42
42
Thank You!!
Topic archived. No new replies allowed.