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?
You need to do: int * const ptr; to make a constant pointer, so that the rule will apply to it. Also note that this is one reason I prefer to consistently put const after the type: int const instead of const int .
Yes. Although this is not necessarily recommended, it can be easily accomplished with the correct set of macros and a header file. Typically, you should declare variables in C files and create extern definitions for them in header files.
All functions, constants, and types that are intended to be used outside the file should be declared in a header file. Static functions, file-local constants and types should be declared at the top of the . c file.
You use the Const statement to declare a constant and set its value. By declaring a constant, you assign a meaningful name to a value. Once a constant is declared, it cannot be modified or assigned a new value. You declare a constant within a procedure or in the declarations section of a module, class, or structure.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With