开发者

Organizing C code in my Xcode project

I want to include a few straight C functions in my Objective C project. Simple stuff like this:

CGPoint vectorSum (CGPoint point1, CGPoint point2) {
    return CGPointMake(point1.x+point2.x, point1.y+point2.y);
}

What is the best way to keep things organized?

In particular, I notice that when I go to create a .c file, it gives me an option to create a header file. Is that a useful thing to do?

EDIT -- adding more detail:

I can get everything to work by telling Xcode to create an Objective-C class "VectorSum", deleting the actual class header and implementation, defining the above function vectorSum in the implementation file, and having the header file contain the following:

#import开发者_如何学Python <Foundation/Foundation.h>

CGPoint vectorSum (CGPoint point1, CGPoint point2);

This works, but it feels "wrong" . . . why am I starting out by creating an objective C class when what I really want is C code?

However, if I try to do this with Xcode's option to create a straight C file, I can't get it to work. If I don't import the foundation, the compiler complains that it doesn't know what a CGPoint is. And if I do import the foundation, I get a zillion compiler errors, presumably because Xcode is trying to read the foundation as C code.


Plain C code can't import objective-C frameworks (Cocoa / Foundation / etc).

Instead, include the relevant C-based frameworks...

e.g.

#include <ApplicationServices/ApplicationServices.h>

or

#include <CoreFoundation/CoreFoundation.h>

Xcode doesn't provide an option to add a simple .m file to the project, but you can just add a .c file, and then rename it to a .m without any problems.

The header file will be useful so that your other code can include it to get the declarations of your helper functions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜