Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const vs static const in anonymous namespace

I want to be able to provide a default name to a class so that I can always have a reasonable name to use when logging errors. I don't need (or want) this name to be a part of the class itself. This default name will never change and so is a good candidate for being const or even constexpr but you can't do constexpr QString or constexpr std::string for whatever reason.

In my cpp file, is it better to do

namespace {
 const QString NAME("Some Name");
}

or

namespace {
 static const QString NAME("Some Name");
}

I know that both versions will result in NAME having internal linkage, but what is best practice? I've seen several discussions on moving global variables to an anonymous namespace but none of them mention using static inside the namespace.

References:

  • http://www.goldsborough.me/c/c++/linker/2016/03/30/19-34-25-internal_and_external_linkage_in_c++/

  • What is external linkage and internal linkage?

  • Unnamed/anonymous namespaces vs. static functions

  • https://softwareengineering.stackexchange.com/questions/297059/static-globals-and-anonymous-namespaces-in-c

like image 482
Aaron Fine Avatar asked Sep 18 '25 15:09

Aaron Fine


1 Answers

static is completely redundant in an anonymous namespace. It does nothing.

Leave it out since it adds nothing but noise and extra typing in that context. Tools like clang-tidy will even generate a warning about it being redundant (depending on options used), so leaving it out also cuts down on noise from tools.

like image 99
Jesper Juhl Avatar answered Sep 20 '25 06:09

Jesper Juhl