#import functions into multiple source files
I have a header (.h
) file that I've defined a bunch of mathematical functions in, for example this one that calculates atmospheric refraction...
float calcAtmosRefraction(float h0) {
float ref = 0.0;
if (h0 > 85) {
ref = 0.0;
}
else if (h0 > 5) {
ref = (58.1 / tan(degToRad(h0)) - 0.07 / pow(tan(degToRad(h0)), 3) + 0.000086 / pow(tan(degToRad(h0)), 5)) / 3600;
}
else if (h0 > -0.575) {
ref = (1735 + h0 * (-518.2 + h0 * (103.4 + h0 * (-12.79 + h0 * 0.711)))) / 3600;
}
else {
ref = -20.772 / tan(degToRad(h0)) / 3600;
}
return ref; // in degrees
}
... and in my main UIViewController's
implementation file I use #import
to add the header. It works fine and I can use the functions. The problem occurs when I want to use these functions in a different UIViewController.
I开发者_运维技巧f I don't #import
the header, I get an implicit declaration
warning for the function name, and if I do #import
the header, I get a duplicate symbol
error.
One way you can do this is to use a combination of a .h
and a .m
file:
Your .h
should look like this:
extern float calcAtmosRefraction(float h0);
And your .m
should have what you have above. #import
the .h
file and you'll be good to go.
Another way you can do this is make the function static
so it doesn't get redeclared. This approach allows you to use only one .h
file.
If your function is defined in the header (and it doesn't have a definition that lives elsewhere), then declare it static
or inline
.
You're getting a duplicate symbol error because C and C++ (and by extension, Obj-C and Obj-C++) disallow multiple definitions of a single function. Either static
or inline
will eliminate the multiple definition error.
精彩评论