Already defined in login.obj

closed account (DEhqDjzh)
I am trying to create a porgram that have all the global variables in OS.h but it gives this error:
SLNK2005 "int userid" (?userid@@3HA) already defined in login.obj

OS.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#pragma once
#include <iostream>
#include <stdio.h>
#include <Windows.h>
#include <experimental/filesystem>
#include <fstream>

#define log(x) std::cout << x
#define loge(x) std::cout << x << std::endl;
#define get(x) std::cin >> x
#define gete(x) std::cin >> x >> std::endl;



int userid;
namespace fs = std::experimental::filesystem;
 

Login.h
1
2
3
4
#include "OS.h"
bool login()
void intro()
 

OS.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
#include "OS.h"
#include "login.h"
int main()
{
	if (login() == true)
	{
		loge("succes");
		system("pause");
	}



}

Can you post the fixed code ?
If you define a global variable in a header file, it will be defined multiple times – once for each source file that header file is (eventually) included in. Remember that header files are basically just copy/pasted into the source files.

The fix is to use extern in the header file, and define it in just one cpp file:
1
2
3
4
5
6
7
// A.h
#ifndef A_H_INCLUDED
#define A_H_INCLUDED

extern int A;

#endif // A_H_INCLUDED 

1
2
3
// A.cpp
#include "A.h"
int A = 0;

1
2
3
4
5
6
// B.cpp
#include "A.h"
int main() {
    std::cout << A << std::endl;
    return 0;
}
Last edited on
closed account (DEhqDjzh)
@TwilightSpectre I cant use extern for namespace
You don't need it for namespaces aliases (or typedefs or using-declarations or function prototypes or...), only for variables – they're just aliases rather than actual "objects", and hence can be redefined in different object files with no consequence.
Last edited on
If you define a global variable in a header file, it will be defined multiple times

Note that, in C++, this is only a problem for non-const variables. If you define a file-scope const variable, it has internal linkage only, so it's no problem if you have them defined multiple times in different translation units.
Topic archived. No new replies allowed.