1

In XCode 8, when I add a new iOS header file to my project, it comes with this code already in it.

#ifndef SomeCoolWidget_h
#define SomeCoolWidget_h

#endif /* SomeCoolWidget */

Is there a good reason I shouldn't delete those directives and just do the usual ...

@interface SomeCoolWidget
...
@end

I have never left those compiler directives in our code and it has never caused a problem, but if there's no issue, I'm then left to wonder why that template is the default for every new header file.

shallowThought
  • 19,212
  • 9
  • 65
  • 112
Logicsaurus Rex
  • 3,172
  • 2
  • 18
  • 27

2 Answers2

1

@interface SomeCoolWidget... is a "Cocoa Touch Class". There is an extra template for it and it creates a Class.h and Class.m file:

For a pure C header file, you do want the preprocessor directives. You can find some background why in this answer.

shallowThought
  • 19,212
  • 9
  • 65
  • 112
1

Those are called macro guards basically preprocessor is checking that if SomeCoolWidget is included in your project before, if it is included it is returning a blank header file.

Another idea is when you have a bunch of related header files you want to prevent recursion.

Let's say A.h -> includes B.h and then B.h -> includes A.h , you dont want that in your code...

Finally let's say you have a Play.h and a Record.h , you can put them in your SomeCoolWidget header then use SomeCoolWidget header to both play and record in some other class.

#import "Play.h"
#import "Record.h"

So @interface SomeCoolWidget usage is different then SomeCoolWidget.h usage. You need to choose whatever suits your needs

SpaceDust__
  • 4,844
  • 4
  • 43
  • 82
  • But doesn't `#import` automagically prevent recursion. Wasn't that the purpose of using it instead of `#include` – Logicsaurus Rex May 22 '17 at 21:43
  • No it doesn't , to me it is just a way of helping to organize my code and write clean code. If you wanna break your code by recursive importing, it is not gonna stop you. – SpaceDust__ May 22 '17 at 21:46
  • you can check this thread for further info https://stackoverflow.com/questions/1653958/why-are-ifndef-and-define-used-in-c-header-files – SpaceDust__ May 22 '17 at 21:48
  • u.gen -- That's not what tons of people say here... https://stackoverflow.com/questions/439662/what-is-the-difference-between-import-and-include-in-objective-c It specifically says that `#imports` prevents recursion. – Logicsaurus Rex May 22 '17 at 21:56