Friday, July 24, 2020

Using Objective-C Runtime to Make Header-Only Files

The original problem
Duplicate symbol errors occur when multiple definitions for a class appear in different translation units. The Gateware isolation tests are written to produce these errors. The goal is that the tests will fail to cause the errors, which is the case on each supported platform with the exception of the Mac. Gateware creates Objective-C classes on the Mac which cannot be inlined like in C++. Because of this limitation, Gateware fails the isolation tests on the Mac, and the linker throws duplicate symbol errors.

The solution
With inlining the class definitions impossible, the popular alternative is to separate the interface and implementation of classes into separate files. Gateware is released as a header-only file, therefor any solution involving adding additional files is not to be considered. Utilizing the Objective-C Runtime Library is the only suitable solution.

Why this works
The Objective-C Runtime Library can be used to create Objective-C classes using C. These classes are created at runtime, therefore avoiding the linker, and thus never causing duplicate symbol errors. To make sure the runtime library would work for Gateware, I ran some tests on a spike solution. With those tests successful, I converted one of the Gateware libraries to use it. Not only did the library pass the isolation tests, it also passed all the Unit Tests with no discernible difference in behavior and execution speed.

Turning it into macros
The first library converted to use the Objective-C Runtime Library to make Objective-C classes took a considerable amount of time while adding a significant number of uneasy to read function calls. To speed up the process and make the code more legible, I wrote macros that took care of most of the work to define a class and use it. The subsequent libraries took a quarter of the time to convert than the first.

Case closed
At the time of this writing, I still have a few more libraries to convert. However, the tough ones are out of the way and all tests are passing. The only other thing left to do now is to update the developer forums I posted to, and inform them of the solution. Ultimately, this solution means Gateware users can expect a more seamless experience developing across platforms.

No comments:

Post a Comment