kyb kyb - 2 months ago 13
C Question

Extern "C" constant value is not known in .cpp but works in .c

In C file

// f1.c
const uint8_t C_VAL=2;`


In C++ file I declare simple array

// f2.cpp
extern "C" const uint8_t C_VAL;
char charray[C_VAL];



Build output:
#259: constant value is not known



There was not any errors when I link extern in .C

// f2.c
extern const uint8_t C_VAL;
char charray[C_VAL];


Works fine.

Seems the problem is with linkage. Is it possible to fix, how? Is this problem only in MDK-ARM or other compilers have too?

Answer

C supports variable length arrays (since C99, but only optionally since C11. Some earlier compilers support them as a language extension), so the value of C_VAL doesn't need to be known at the time f2.c is compiled and so there isn't a problem.

C++ doesn't support variable length arrays (except some compilers support them as a language extension), so the value of C_VAL must be known at the time f2.cpp is compiled. Since it is merely declared, its value is not known and that is why the compiler shows you the quoted error. The value remains unknown until the object files of f2.cpp and f1.c are linked together.

Solution: Either use a language that supports VLA (such as C99), or a compiler that supports VLA as an extension (see the manual of your compiler whether it supports it, and how to enable the support) or define the array with a length that is known at compile time.

Comments