2

I know from these questions that if I declare a static const variable in a header file:

Foo
{
public:
    static const int BAR = 1234;
    ...
};

I must also define it in a source file:

const int Foo::BAR;

However, it gcc will happily ignore this requirement if the variable isn't used in the program. Furthermore, gcc seems to happily gloss over some simple uses (e.g. passing to std::min by const reference) if optimization is enabled.

Is there a way to force gcc to warn if I've forgotten to provide a definition even if the variable isn't used in my source code? If Foo above is part of a shared library and no definition for Foo::BAR is provided, users wouldn't be able to pass Foo:BAR by reference or get a pointer to it, but I as the library writer am given no indication that this is a problem.

More generally, is there a way to enforce that all declarations in a shared library have a corresponding definition? Or would this be sacrificing too much in the way of optimization opportunities to be worthwhile?

Community
  • 1
  • 1
Alec
  • 583
  • 3
  • 21
  • 1
    In referenced and undefined in .cpp file `const int Foo::BAR` is not much different from `void Xyz(int, char*);` that has has no body and is never called. – Kirill Kobelev Jan 05 '16 at 01:17

1 Answers1

1

You tagged this question with language tags so...the code is technically legal as the standard only requires the definition when it is used in the final program. The compiler has no idea if you are going to link against another translation unit that defines the symbol so even generating a warning would be tricky and probably generate false positives.

The easy way to check is to properly unit test your library interface (as suggested in a comment), then you'll know for sure right at the point you link the unit test.

Mark B
  • 95,107
  • 10
  • 109
  • 188