3

I’m writing a c++ application which does lots of string parsing. I keep my string definitions in a normal header file (there is no corresponding C++ file).

The header file uses #ifdef XXX to ensure its processed by the compiler only once.

I have the option of declaring the strings either

const TCHAR m_szRoot[] = _T("root");

or

static const TCHAR m_szRoot[] = _T("root");

Theses variable are used numerous times in the application.

What’s the recommended declaration? and which declaration is better from an application size perspective.

Joseph King
  • 5,089
  • 1
  • 30
  • 37

2 Answers2

3

If you make the same static from a header included in multiple translation units, each resultant file would get its own copy of the object, potentially increasing the footprint of your application. Moreover, the objects would reside at different addresses, potentially making equality comparisons slower. Link-time optimization can combine identical constants, but that would be optional.

A certain way of avoiding duplicates would be placing your constants in a separate translation unit (i.e. a CPP file), and using extern in your header file.

Header:

extern const TCHAR m_szRoot[];

constants.cpp:

const TCHAR m_szRoot[] = _T("root");

This would ensure a single definition for each constant.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • I just had a thought - doesn't the `const` already imply internal linkage? – Joseph Mansfield Mar 23 '13 at 10:52
  • However, link-time optimization can, and often does, combine duplicate strings. That's why the language definition is careful not to insist on separate addresses for identical strings defined in different translation units. So making them `static` may not have as big an impact as it at first appears. – Pete Becker Mar 23 '13 at 10:56
  • 5
    `const` also says `static`, unless it's explicitly marked `extern`. `const int i = 3;` is the same as `static const int i = 3;`. – Pete Becker Mar 23 '13 at 10:58
  • @dasblinkenlight As Pete Becker says, `const` implies internal linkage in C++. See [dcl.stc]§7. – Angew is no longer proud of SO Mar 23 '13 at 10:59
  • @PeteBecker Wow, that's nice to know, thanks! This explains why the OP is not getting duplicate symbols at link time. – Sergey Kalinichenko Mar 23 '13 at 11:01
2

Forget micro-optimizations!!

Use static if you want to limit the scope of the variable to a single translation unit.
static gives you internal linkage.
That should be the criteria to declare it static and not the optimizations. The compiler will do whatever optimizations are needed to be done.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • @SeanieO'Leary: [What is a “translation unit” in C++](http://stackoverflow.com/questions/1106149/what-is-a-translation-unit-in-c) – Alok Save Mar 23 '13 at 10:51