Initialize Variable in Header File

I have a variable that needs to start with a default value. I have a function in the .cpp file for that header file that changes variable a with every run. However, the variable must have a value and be initialized to run that function in the first place. At this moment, I can't run that function because I can't initialize the variable in the header file, or basically give it a default value.
I don't know why you can't initialize a value in your header, you should be able to do it.
However, another solution might be to initialize it in your constructor. It should work since constructor is the fight thing called by default when you run the program.
I'm a bit unclear what you asking, but...

If a header file is included in multiple cpp files then initialising (and hence defining it) a variable in it will break the one definition rule. The variable must be only declared in the header and then defined (and initialized) in a single .cpp file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// main.cpp

#include <iostream>
using namespace std;

#include "example.h"

int value = 123; // definition

int main() {
    cout << "Hello world!\n";
    test();
    return 0;
}


1
2
3
4
5
6
7
8
9
10
// example.h

#ifndef Included_Example_H
#define Included_Example_H

extern int value; // declaration

void test();

#endif // Included_Example_H 


1
2
3
4
5
6
7
8
9
10
// example.cpp

#include <iostream>
using namespace std;

#include "example.h"

void test() {
    cout << "value = " << value << "\n";
}


Andy
Last edited on
Topic archived. No new replies allowed.