Non-const variable for global use ..?

Hello.
I have a common.h file containing only:
const int i = 1;
main.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
#include "common.h"

void This()
{
   printf("In This, address is %p\n", &i);
}

int main()
{
    i=1; //ERROR
   This();
}

These 2 files are only examples representing my problem.
I want to have a variable accessible to all of my .cpp files (and are many!!!)
The problem is that I want to be able to change the value of these variables. Unfortunately the variables are read-only and i get error: assignment of read-only variable ā€˜i’
This is logical but if instead of 'const int' I use 'int', then I get error: multiple definition of ā€˜i’ (not in this specific example, but if I include common.h in some other .cpp file it will say multiple definition.)

So, what I want is to create a variable into common.h that its value can be changed by every .cpp file. 'int' instead of 'const int' cannot be used because of multiple definition error.

thx in advance :)
Last edited on
const int i = 1 in your header file should be changed to
extern int i;

Add this to main.cpp after the header files:
int i = 1;
Thanks, his works fine with one .cpp file. But what if I want the variable in more than one .cpp file?
E.g.
//mian.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
#include "common.h"
int i = 1;
void This()
{
   printf("In This, address is %p\n", &i);
}

int main()
{
    i=1; //ERROR
   This();
}

lol.cpp
1
2
3
#include <stdio.h>
#include "common.h"
int i = 1; //ERROR I GET MULTIPLE DEFINITION ERROR AGAIN! 
The neat thing about extern is that it declares that a variable's actual code is in another object file, but still permits the variable to be known about in other files. So you only need that int i = 1; in one file. :)

-Albatross
Thanx a lot
Topic archived. No new replies allowed.