user392412
user392412

Reputation: 743

Why do I need using "extern static" to define a constant in header file in Objective-C?

I know using static const to define a constant is better than use #define.

But in this SO question, why use **extern** static const in header file, and write another m file to actually define the value. Why not just use static int const kMyVar = 1; in header file and no more m file instead?

Upvotes: 1

Views: 1272

Answers (3)

Jeffery Thomas
Jeffery Thomas

Reputation: 42588

You should not use extern static. You should only use extern.

File.h

extern const int MyGlobalConstant; // NOTE: Not static

File.m

const int MyGlobalConstant = 12345; // NOTE: This is not static either

This creates a memory location in File.m which other files that import File.h can reference.

In contrast,

File.h

static const int MyGlobalConstant = 12345;

This creates a separate and distinct memory location in every .m file which includes File.h.

The difference is important. In the first example, you have 1 MyGlobalConstant. In the second example, you will have tens if not hundreds of separate MyGlobalConstants all with the same value.

It's more than just a waste of space. I can cause problems debugging and problems for a profiler.

Upvotes: 6

pqnet
pqnet

Reputation: 6588

static const int myvar declares that in this translation unit (e.g. the resulting object file for this compilation step) there should be a static variable of type int named myvar. The memory is allocated, statically, by the compiler in this object file.

extern static const int myvar declares that somewhere in the program there is a constant variable named myvar, but do not specify where this variable is allocated or what its value is: it will be the linker that replaces the address of this variable with the actual address of the variable when it links the translation unit where this variable is allocated. In some way the extern static specifier introduces a variable declaration, while the form without extern introduces a variable definition.

Upvotes: 0

audun
audun

Reputation: 154

You don't want to use static in this case, because then it will be defined for each compilation unit that include your header file.

With an int there won't be any problem, but when you introduce e.g. strings you can end up with multiple declarations and then the fast stringInstance == MyFirstConstant pointer comparison technique will not work.

Upvotes: 0

Related Questions