On Jun 1, 2011, at 8:17 AM, Graham Cox wrote:
>
> On 02/06/2011, at 1:12 AM, JAMES ROGERS wrote:
>
>> K&R says to declare and initialize an array in C:
>>
>> int myArray[2] = {1,2};
>>
>> If the above is entered into the .h file
>
>
> That's because a .h file is the HEADER.
>
> You need to put this in the BODY, which is the .c (pure C) or .m (Obj-C)
> file. The reason is that the = {1,2} part is executable code, not just a
> declaration, so it needs to live somewhere.
It's true the initializer shouldn't go in the .h file, but not because its
executable.
Technically, it isn't. The initialization of globals is done at compile time,
not at run time.
And the compiler doesn't know the difference between a .h file and a .c file
anyway. The preprocessor (which does not understand C) expands #include into
the contents of the included file, and the compiler itself only sees the merged
result. Thus, the compiler has no knowledge of which file a particular line
comes from. (Except for error messages, but that's a side channel.)
The problem is that while globals can be declared in as many compilation units
as you wish, they must be defined in only one. That means that a definition
cannot appear in a file that's #included into multiple compilation units.
It would be perfectly fine to put that initializer in a .h file, as long as the
.h file is #included into only one .c file. That's not how we normally use .h
files, though, because it would make the name visible in only the one
compilation unit that included it. The whole point of having separate .h and
.c files is to work around the "declared in multiple units: OK, defined in
multiple units: BAD" limitation, without giving up the safety of "declared in
multiple source files: BAD"._______________________________________________
Cocoa-dev mailing list ([email protected])
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com
This email sent to [email protected]