I have the following file testf.h:
#ifndef TESTF_H_
#define TESTF_H_
int test(int what){
return what;
}
#endif
I included/imported it in TestAppDelegate.h (which is used for other .m files in my xcode project). I get a duplicate symbol error. If I included/imported testf.h in a .m 开发者_开发问答file that is never included/imported in other files then it works fine. So it seems like the #ifndef/#define/#endif
has no effect. Is there anyway to go around this?
Thanks
This is a function definition, it belongs in a c, cpp or m file.
This popular trick with #defines will protect you from compiler errors (typically to survive circular #include dependencies. ) It will not protect against a linker error. This is exactly why people put declarations in h files and definitions in c (or m) files.
Including function definitions (as opposed to declarations) in header files is generally a bad idea and now you know why. You want two separate files, the header would look like this:
#ifndef TESTF_H_
#define TESTF_H_
extern int test(int);
#endif
And then a .c
file (or possibly a .m
file if you want to use Objective-C rather than plain C) like this:
int test(int what) {
return what;
}
The header file will let the compiler know what test
is, what it returns, and what arguments it should take; that's enough information for the compiler to arrange a call to test
; that's actually more information than the compiler needs but some of us like our compilers to do some error checking. The C source file will (after being compiled into a object file) let the linker know what code the test
symbol resolves to.
Right now you're ending up with multiple globally visible instances of the test
symbol, one for every file that has included your testf.h
.
The other option, for a simple function, is to declare it inline
:
inline int cNorm(float _amp) {
return 42;
}
精彩评论