How to define const int in .h file properly?
In a project, I need to define a const int, I define开发者_StackOverflow it in a header as:
extern const int a;
And I include that header many times. Then in only one source file, I put:
const int a=10;
However when I need to use a in an array bound; i.e.:
int anarray[a];
I get:
"array bound is not an integer constant"
error. Why?
An array bound has to be an integral constant-expression. To be an integral constant-expression an expression must only involve (amongst a few other things) literals, enum
values and const
variables or static
data members only if they are initialized with constant-expressions.
const
variables of integer type are not integral constant-expressions if they don't have a initializer.
It's a language rule that allows implementation to know certain constant values at compile time without having to know about other translation units (which may not be compiled at the same time and which may be changed independently).
const
variables at namespace scope have internal linkage by default (i.e. without an explicit extern
) so you won't have any multiple definition problems if you do something like this.
// header.h
const int a = 10;
.
// source.cpp
int anarray[a];
The array dimension needs to be known at compile time. For constants such as this you might want to consider using an enum instead. That way its value is visible in the header and you still get the symbolic name when debugging (unlike using a #define).
// foo.h
enum {
a = 10; // array dimension
};
and
// foo.c
#include "foo.h"
int anarray[a];
The value of a constant needs to be known at compile-time. extern
variables are not so: if at all, their values can only be determined at link-time, which comes after the compilation step. So as far as the compiler is concerned, an extern
is not a constant.
精彩评论