0

In my Xcode project I made a standalone header file with the following C utility function:

#ifndef FOO
#define FOO
CGFloat DistanceBetweenTwoPoints(CGPoint p1, CGPoint p2)
{
    CGFloat dx = p2.x - p1.x;
    CGFloat dy = p2.y - p1.y;
    return sqrt(dx*dx + dy*dy);
};
#endif

Even with the preprocessor directives, if I try to import or include that header file in multiple locations, I receive the following error complaining about duplicate symbols:

linker command failed with exit code 1

Is there a different way I can achieve this effect? This question is out of curiosity more than anything else.

Thanks

2 Answers 2

1

Put your function body in a .c file and the function declaration (aka prototype) in the .h with those #ifndef, etc. Then use include to import the header file where you need the function.

Remember to check the target membership of the .c file, otherwise it won't be compiled.

For a small function like that you can declare it inline and just use the header file:

inline CGFloat DistanceBetweenTwoPoints(CGPoint p1, CGPoint p2)
{
    // code as is
}

The compiler will replace your function calls with the function code without actually building and linking a new object file. No more duplicated symbols.

Sign up to request clarification or add additional context in comments.

Comments

1

Since the function's definition is in the header, you get one definition of the function in each file (actually, each translation unit) where it is included.

Move the function body into a ".c" file, leaving a declaration in the header, or declare it inline.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.