Person.h
Code Block Objective-C #ifndef Person_h #define Person_h @interface Person : NSObject -(void)speak; @end @implementation Person -(void)speak { // Say something } @end #endif /* Person_h */
I also have two source files that both include the header file.
Main.mm
Code Block Objective-C @import Foundation; #import "Person.h" int main(int argc, const char * argv[]) { // Do nothing }
Test.mm
Code Block Objective-C @import Foundation; #import "Person.h"
When the project is built, I get duplicate symbol errors.
Code Block duplicate symbol '_OBJC_CLASS_$_Person' in: /Debug/TestBox.build/Objects-normal/x86_64/main.o /Debug/TestBox.build/Objects-normal/x86_64/test.o duplicate symbol '_OBJC_METACLASS_$_Person' in: /Debug/TestBox.build/Objects-normal/x86_64/main.o /Debug/TestBox.build/Objects-normal/x86_64/test.o ld: 2 duplicate symbols for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)
I want to be able to include the same header file in multiple source files. In C++, I can inline the implementation into the header file like this:
Code Block C++ #ifndef Person_h #define Person_h class Person { public: void speak() { // Say something } }; #endif /* Person_h */
However, I haven't been able to find a way to do that with Objective-C. I'm using Objective-C so I can subclass events from NSWindowDelegate and NSResponder.
I tried searching for solutions. Most of them said to separate the implementation into a source file, but that would break the single-header architecture. One suggestion is to use the Objective-C runtime library and create my classes at runtime. This appears to give me the results I'm looking for, but I'm wondering if there is a simpler way.
Is there some way to implement an Objective-C class in a header file so that can be included by multiple source files? Or is dynamically creating the classes at runtime my best option?