Visual Studio LNK2005 Error help D:

closed account (ivDwAqkS)
I just downloaded Visual Studio 2013, its my first time to use this compiler,
but I just wanted to test this compiler for first time
and I got an error. can you tell me where is the error?
its suppose that with #ifndef shouldn't give me an error.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*Data.h
I declared named arr to my array;
in my header cant I declare an array without setting the numbers elements?
coz when I did it it told me error, 
however when I used code blocks I could do it but all my program was in one file
*/
#include <iostream>
using namespace std;

#ifndef DATE_H
#define DATE_H
int arr[10] = {};
void function();
#endif
/*main.cpp
**********************/
#include "Data.h"

int main(){

	function();
	cout << endl << endl;
	return 0;
}
/*function.cpp
#include "Data.h"
it says that here is the error, that my arr is already defined
***********************/
void function(){
	for (int i = 0; i < 10; i++){
		arr[i] = i + 1;
		cout << arr[i] << " ";
	}
}
/*Error	1	error LNK2005: "int * arr" (?arr@@3PAHA) already defined in function.obj
Error	2	error LNK1169: one or more multiply defined symbols found*/

when I put const int arr[10]={}; it works but there is another error, it doesn't let me to change the values coz its constant obviously -.-.
Last edited on
You can't put global vars in header files. At least not like that.

The real solution here is to rethink where 'arr' is placed. It should probably be owned in main(), and should be passed to 'function' as a parameter.

Though if you must use a global... you can. You just have to do it right. See this post for details:

http://www.cplusplus.com/forum/windows/115425/#msg636078
closed account (ivDwAqkS)
i try to use extern int arr[10] = {}; and doesn't work
That's only half of what you need to do.

But again... the better solution here is to not use globals at all. Learn to pass things to/from functions.
closed account (ivDwAqkS)
thanks that's what i wanted to read :D.
Topic archived. No new replies allowed.