0

I have a header file containing multiple constexpr variables like the following:

namespace AAA {
constexpr const char* A = "abc";
constexpr std::array B = {"aaa", "bbb"};
}

namespace BBB {
constexpr const char* C = "def";
constexpr std::array D = {"ccc", "ddd"};
constexpr const char* E = "efg";
}

This header is used in multiple projects (separate parts of the code). When trying to build, I get something like: error: 'AAA::B' defined but not used.

I do not get the error for BBB::D, although neither of the variables are used in the translation units that yield the error.

If I change the third line to

constexpr std::array<const char*, 2> B = {"aaa", "bbb"};

compilation goes through (although I have not changed constexpr std::array D = {"ccc", "ddd"};).

Adding static keyword does not affect the outcome. Adding template parameters for BBB::D and not adding it for AAA::B does not help either.

Any ideas what the reason is?

KMot
  • 467
  • 5
  • 13
  • 3
    Whereas gcc only warns for first unused `constexpr array` (i.e commenting `B` results in warning for `D`), clang warns for all of those constexpr variables [Demo](https://godbolt.org/z/q5h8vqjxW). – Jarod42 Feb 13 '23 at 16:50
  • 1
    BTW, you got error as you treat warning as error. – Jarod42 Feb 13 '23 at 16:53
  • 4
    Making all of the variables `inline` gets it to compile on all of the compilers in Jarod's link. You really should be doing that anyways with variables defined in a header file. – NathanOliver Feb 13 '23 at 16:59
  • Thanks a lot! That is very helpful. The remaining question is why adding template parameters to std::array (i.e. ) avoids the warning. And by the way, why does it complain about AAA::B, and not AAA::A in the first place? Could it have something to do with the std::array being a class and char* being a primitive type? – KMot Feb 13 '23 at 22:39
  • @NathanOliver, `consexpr` should imply `inline` for static variables, but as mentioned adding `static` keyword (or `inline`) does not help in my real use case. (why? :-| ) Please see the 2nd answer here: https://stackoverflow.com/questions/14391272/does-constexpr-imply-inline – KMot Feb 14 '23 at 09:26
  • @KMot `inline` for static variables only applies to class member static variables. Non-class member statics do not get that and must explicitly be declared inline. – NathanOliver Feb 14 '23 at 13:00
  • *"why does it complain about `AAA::B`, and not `AAA::A` in the first place?"* Clang does. Maybe gcc just ignores "trivial" types. – Jarod42 Feb 17 '23 at 16:49

0 Answers0