Compiling C using Objective-C and duplicating character linker errors (iPhone related)

I have the following testf.h file:

#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 character error. If I included / imported testf.h into a .m file that is never included / imported into other files, then it works fine. It looks like #ifndef/#define/#endif has no effect. Should I get around this at all?

thanks

+4
source share
3 answers

This is a function definition; it belongs in the file c, cpp or m.

This popular C # defines trick will protect you from compiler errors (usually to preserve #include looping dependencies.) It will not protect against linker errors. That is why people put declarations in h files and definitions in c (or m) files.

+4
source

Including function definitions (as opposed to declarations) in header files is usually a bad idea, and now you know why. You want two separate files, the header will look like this:

 #ifndef TESTF_H_ #define TESTF_H_ extern int test(int); #endif 

And then a .c file (or maybe a .m file if you want to use Objective-C, not just C), like this:

 int test(int what) { return what; } 

The header file will let the compiler know what test , what it returns, and what arguments it should accept; that there is enough information for the compiler to organize the test call; which is actually more information than the compiler needs, but some of us, like our compilers, do some error checking. The C source file (after compilation into an object file) allows the linker to find out what code the test character allows.

Currently, you get several instances of the test symbol visible worldwide, one for each file that includes your testf.h .

+4
source

Another option for a simple function is to declare it inline :

 inline int cNorm(float _amp) { return 42; } 
+1
source

All Articles