Declare and initialize constant in header file

Patrick Perini picture Patrick Perini · Jun 25, 2012 · Viewed 26.5k times · Source

I'm well versed in the typical paradigm of:

//.h
extern const int myInt;

//.c, .m, .cpp, what have you
const int myInt = 55;

But there's got to be a way to put that into .h files for use with libraries or other instances where you cannot access the implementation file.

For example, I'm trying to add an NSString constant to a .h file in an Xcode project like so:

static NSString *const myString = @"my_string";

however, when I attempt to use myString, I get the error

Initializer element is not a compile-time constant

on myString, indicating that it is not being properly instantiated. How does one declare compile-time constants in a C++ or Objecitve-C header file?

Answer

CB Bailey picture CB Bailey · Jun 25, 2012

In C++, const objects have internal linkage unless explicitly declared extern, so there is no problem with putting a definition into a header file such as:

const int myInt = 55;

With this definition and first declaration, myInt can be used as an integer constant expression such as for array bounds and the like.

I can't answer for Objective C.