Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare and initialize constant in header file

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?

like image 983
Patrick Perini Avatar asked Jun 25 '12 17:06

Patrick Perini


People also ask

How do you declare a constant in a 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 .

Can we initialize variable in header file?

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.

Should constants be defined 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.

How do you define and declare constant?

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.


1 Answers

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.

like image 50
CB Bailey Avatar answered Sep 22 '22 07:09

CB Bailey