Question about static variables

Pages: 12
When I said "if it was working properly" I didn't mean to suggest that it isn't proper for it to complain. Just that if what I was trying actually worked, it wouldn't have complained about the VLA (which I know is non-standard since I tell people that all the time).

Anyway, I obviously don't understand how extern and const work together. Perhaps they simply don't. So here'a s version of my original example that works.

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// main.cpp
#include <iostream>
#include "settings.h"
#include "f.h"

int main() {
    std::cout << settings.a << '\n';
    f();
    std::cout << settings.a << '\n';

    int a[settings.c]{};
    for (int i = 0; i < settings.c; i++) std::cout << a[i] << ' ';
    std::cout << '\n';
}

// settings.h
#ifndef SETTINGS_H_
#define SETTINGS_H_

struct Settings {
    static int a;
    static int b;
    static const int c = 10;   // must be initialized here
};

extern Settings settings;

#endif


// settings.cpp
#include "settings.h"

int Settings::a = 1;
int Settings::b = 2;


// f.h
#ifndef F_H_
#define F_H_

void f();

#endif


// f.cpp
#include "settings.h"

void f() {
    settings.a = 42;
}


$ g++ -std=c++11 -Wall -Wextra -pedantic -c main.cpp
$ g++ -std=c++11 -Wall -Wextra -pedantic -c settings.cpp
$ g++ -std=c++11 -Wall -Wextra -pedantic -c f.cpp
$ g++ -std=c++11 -Wall -Wextra -pedantic main.o settings.o f.o
$ ./a.out
1
42
0 0 0 0 0 0 0 0 0 0 

@tpb, & FurryGuy
Thanks a lot for taking the time to test and explain this out, this is very much appreciated!

So I guess I'd better either put my const in a structure or define them in the header file straight away.

It's nice to always keep learning bits here and there, Thanks guys <3!
The size of stack-allocated arrays needs to be constexpr (i.e. a compile-time constant). const sometimes implies constexpr, but not always. If you have declared a variable as extern const, without defining it, the value is not known so it can't be constexpr.
Last edited on
Thanks for the info Peter87, that makes sense
Topic archived. No new replies allowed.
Pages: 12