Global variable in header file

Hi there!
I'm having another go at trying to split up my code into more files, after giving up several times earlier (And soon about to again!) :P

So in my last project, I started splitting up my code from the beginning, but it didn't take long until I got some shitty linker error. I narrowed the problem down, and found out it was caused by making a global variable in a header file.

This code will produce the error "fatal error LNK1169: one or more multiply defined symbols found".

Main.cpp
1
2
3
4
#include "Main.h"

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow)
{}


Main.h
1
2
3
4
5
6
7
#ifndef MAIN_H
#define MAIN_H

#include <Windows.h>
#include "Test.h"

#endif 


Test.cpp
 
#include "Test.h" 


Test.h
1
2
3
4
5
6
#ifndef TEST_H
#define TEST_H

int i; // Declaring a global variable here will cause a linker error. It compiles fine without this line.

#endif 



So why does this happen? I thought global variables were supposed to be put in header files (Even though I shouldn't use them at all, I know).
If you use i in test.h, you get no errors. If you use i in any other file, it doesn't know which i to use, because it's got two copies. You'll either have to extern int i; or static int i; depending on what behaviour you want.
closed account (S6k9GNh0)
No, in order to use a variable or function, it can only be provided in implementation once.

Basically, what you did was ask for a a variable named "i" in the implementation but it contains multiple variables named "i" so it gives an undefined symbol error as a result.

Also, try not to use global variables.

All a header file does is present what's available in the implementation. If the implementation doesn't contain it or contains multiple definitions of it, it will cause issues.

EDIT: Edit to correct myself.
Last edited on
@computerquip: Did you read the error he got? It says multiply defined symbols, not undefined symbols.
Variable i defined in Test.h has external linkage. So every compilation unit which includes Test.h has definition of i. After compilation of each compilation unit the compiler builds a table of external sybols. And after that the linker sees that there are several external symbols with the same name that are defined in different compilation units.

As already was pointed out you should either declare i as

extern int i;

in Test.h and then in some module define it. Or you can make it visible only inside each module by placing it in unnamed namespace.
Last edited on
Topic archived. No new replies allowed.