开发者

How to make a struct maker like CGRectMake (iphone)

开发者 https://www.devze.com 2022-12-27 12:05 出处:网络
i have a struct HLRange with two CGFloat\'s struct HOLRange { CGFloa开发者_如何学JAVAt min; CGFloat max;

i have a struct HLRange with two CGFloat's

struct HOLRange
{
CGFloa开发者_如何学JAVAt min;
CGFloat max;
};
typedef struct HOLRange HOLRange;

but how do i make a function like HLRangeMake(1,2); .. like CGRectMake?

--EDIT--

my header file

#import <Foundation/Foundation.h>

struct HOLRange
{
    CGFloat min;
    CGFloat max;
};
typedef struct HOLRange HOLRange;

HOLRange HOLRangeMake(CGFloat min, CGFloat max) {
    HOLRange range;
    range.min = min;
    range.max = max;
    return range;
 }

@interface Structs : NSObject {

}

@end


error message: ld: duplicate symbol _HOLRangeMake in             /Users/Documents/projects/iphone/test/catalog/base1/build/base1.build/Debug-iphoneos/base1.build/Objects-normal/armv6/base1AppDelegate.o and /Users/Documents/projects/iphone/test/catalog/base1/build/base1.build/Debug-iphoneos/base1.build/Objects-normal/armv6/main.o


HOLRange HLRangeMake(CGFloat min, CGFloat max) {
    HOLRange range;
    range.min = min;
    range.max = max;
    return range;
}


You can see CGRectMake source in CGGeometry.h so you can do the same:

CG_INLINE CGRect
CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height)
{
  CGRect rect;
  rect.origin.x = x; rect.origin.y = y;
  rect.size.width = width; rect.size.height = height;
  return rect;
}

Edit: You must either define your function as inline or move its implementation to .m file. You're getting linker errors as you function becomes defined in every compile unit that imports HoleRange.h (?) header.


Old post. However, I'd like to share my method of resolving this problem for future viewers.

typdef struct _HOLRange {
    CGFloat min;
    CGFloat max;
} HOLRange;

static inline HOLRange(CGFloat min, CGFloat max) {
    return (HOLRange) {min, max};
}

You can define your stuct and Make function like this. Short and quick.


I like the format of this better. It makes more sense visually and seems more "correct."

typedef struct {
    CGFloat min;
    CGFloat max;
} HOLRange;

static inline HOLRange HOLRangeMake(CGFloat min, CGFloat max) {
    HOLRange range;
    range.min = min;
    range.max = max;
    return range;
}
0

精彩评论

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