15

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?

Patrick Perini
  • 22,555
  • 12
  • 59
  • 88

1 Answers1

19

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.

s3rvac
  • 9,301
  • 9
  • 46
  • 74
CB Bailey
  • 755,051
  • 104
  • 632
  • 656
  • @Vorac: This does work in g++ (assuming that you are actually compiling C++ source code). Your edit caused me to waste time re-verifying something that was already correct and it made this answer internally inconsistent. Why would I say "`const` objects have internal linkage" and then and an _explicit_ `static` to the example? If you are not sure about something then comment; don't edit. I have rolled back your edit. – CB Bailey Oct 12 '12 at 06:54