Reputation: 41
I have a C/C++ mixed project that I am currently working on. I have a global constants C code that I want to be able to access from my C++ scripts and C scripts. In this particular situation I am trying to use a C++ array with variable dimensions made up of constant integers defined in the C global constants code. However, when I try to use or declare this array I get the error that the array dimensions are not integer constants (though I defined them to be integer constants in my C code).
constants.c
const int x = 5;
constants.h
#ifdef __cplusplus
extern "C" {
#endif
extern const int x;
#ifdef __cplusplus
}
#endif
my_cpp.h
#include "constants.h"
my_cpp.cpp
#include "my_cpp.h"
double A[x];
So here, I would get an error stating that x is not an integer constant. Where did I go wrong?
Upvotes: 1
Views: 97
Reputation: 62593
You didn't put definition of x
in the header file, so it is not a core constant expression.
Easiest way to fix would be to use const int x = 5;
in your header file. Alternatively, you can use enum: enum { x = 5; }
- this gives you true prvalue, pretty much like the literal 5
itself.
More information on what is a constant expression in C++ (and array indexes need to be constant expressions in C++) can be found here: https://en.cppreference.com/w/cpp/language/constant_expression
Upvotes: 7