0

I have a project with a lot of c-Files with statements like the following:

static const uint8_t MOD_BIT_POS = 10;
static const uint16_t MOD_SHUTDOWN = 0x0001 << MOD_BIT_POS;

When I try to compile the project, I get the following error:

error: initializer element is not constant
static const uint16_t MOD_SHUTDOWN = 0x0001 << MOD_BIT_POS;

As soon as I change the above code to

static const uint16_t MOD_SHUTDOWN = 0x0001 << 10;

the error disappears.

As I said the project has a lot of files with a lot of lines like this, it is not my code and replacing might not be an option in every occasion, so I would like to resolve this issue. My colleagues do not have the same issue, so it must have something to do with my setup.

I use gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0 on Linux Mint.

The CFLAGS are the following:

-pedantic -Wall -Wformat=2 -Winit-self -Wmissing-include-dirs -Wcast-qual -Wstrict-prototypes -Wnormalized=nfc -Wunreachable-code -Wextra -O2

But my colleagues are using the same, so I would think this can't be the root of the problem.

TigersEye120
  • 664
  • 1
  • 9
  • 28
  • 2
    This is a FAQ but I can't be bothered to look for duplicates. Short version: `const int` variables don't count as integer constant expressions in C, unlike C++. Maybe your colleagues are confused and compile as C++ or something, because this has never worked in C. – Lundin Feb 17 '20 at 16:08
  • That's nothing gcc specific, it's C. `const` in C is basically read-only. – emacs drives me nuts Feb 17 '20 at 16:10
  • [GCC compiles the code with those switches, if `#include ` is inserted and the statements are left at file scope.](https://godbolt.org/z/digUQ_). Maybe you have them in some other context. Show a [mre]. Actually, Godbolt does not offer 7.4, and compilation fails in 7.3 but succeeds in 8.1. Can you upgrade? – Eric Postpischil Feb 17 '20 at 16:12
  • @EricPostpischil But if you switch to GCC 4.4.7, the compilation fails with the expected error. The change in behavior appears in GCC 8.1. – Andrew Henle Feb 17 '20 at 16:15
  • Where did 4.4.7 come into this? In any case, the fact that their colleagues do not encounter the error suggests they are using a later version of GCC and that upgrading would be feasible. – Eric Postpischil Feb 17 '20 at 16:19
  • 4.4.7 was the first earlier version of GCC I tried. This question seems relevant: https://stackoverflow.com/questions/30962512/why-it-is-allowed-to-initialize-static-variable-with-non-const-here Seems like a GCC bug, given even the [draft C2X standard](https://port70.net/~nsz/c/c2x/n2434.pdf) retains the "All the expressions in an initializer for an object that has static or thread storage duration shall beconstant expressions or string literals." wording. – Andrew Henle Feb 17 '20 at 16:24

0 Answers0