سؤال

Apple uses the following code in the header of all its framework classes.

#if !defined(__COREFOUNDATION_CFARRAY__)
#define __COREFOUNDATION_CFARRAY__ 1
...
#endif

Is this a recommended approach for eliminating "duplicate symbol" linker errors, when designing classes or categories for framework use, or are these left over protection from the use of #include instead of #import in c?

Research into this has lead me to this article on include guard

NOTE: this question is not asking how to fix a duplicate symbol error, but instead asking if there is any way of preventing your own code from causing the problem if its included more than once in a project.

هل كانت مفيدة؟

المحلول

You're right about the include guard - there's probably some compatibility reason it's not been removed from the source.

However, this won't really protect you against duplicate symbols much.

For example,

What if you have two third party library, each of which uses the SBJSON library (I had this happen to a colleague a few weeks ago).

Each of the libraries was compiled seperately so, from their point of view, SBJSON was only included once. However, when I came to link my app I couldn't because I had duplicate symbols.

I had to solve this by manually removing the symbols from one of the .a library files (This link shows it's quite a common problem!)

EDIT : This link is a much clearer step by step solution to the problem

نصائح أخرى

Apple uses the following code in the header of all its framework classes.

Not necessarily for the ObjC APIs. But CoreFoundation, yes they use include guards. It's still idiomatic in many camps to use traditional #includes in C sources, and to use #import for objc sources (#import is a compiler extension, not traditional C).

Is this a recommended approach for eliminating "duplicate symbol" linker errors

No, it does not prevent linker errors; it can result in duplicate declaration errors during compile phases.

If you're getting duplicate symbol linker errors, the problem is something else, such as visibility of definition. For that, you should provide an example of your troubling program.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top