Home > OS >  How to use nesting defines from objc/c in swift?
How to use nesting defines from objc/c in swift?

Time:02-19

I have C header with some defines from a library vendor. Defines look likes:

#define TEST_DEFINE_1 0x12340000
#define TEST_DEFINE_2 TEST_DEFINE_1
    
#define TEST_USE_DEFINE_1 (TEST_DEFINE_1| 0x0001)
#define TEST_USE_DEFINE_2 (TEST_DEFINE_2| 0x0001)

I want to use these defines in my swift code, so i added Bridging Header:

#ifndef Bridging_Header_h
#define Bridging_Header_h

#include "defines.h"

#endif /* Bridging_Header_h */

And use them:

print(TEST_DEFINE_1)
print(TEST_DEFINE_2)
print(TEST_USE_DEFINE_1)

// This line causes error "Cannot find 'TEST_USE_DEFINE_2' in scope"
print(TEST_USE_DEFINE_2)

So i can't use nested defines with arithmetic.

Is there problem in swift/xcode? Or am i doing it wrong?

There is repo with minimal example: https://github.com/aatriff/define_test

CodePudding user response:

Check out this documentation for working with C macros in Swift.

Here are the relevant parts:

Swift automatically imports simple, constant-like macros, declared with the #define directive, as global constants. Macros are imported when they use literals for string, floating-point, or integer values, or use operators like , -, >, and == between literals or previously defined macros.

C macros that are more complex than simple constant definitions have no counterpart in Swift. You use complex macros in C and Objective-C to avoid type-checking constraints or to avoid retyping large amounts of boilerplate code. However, macros can make debugging and refactoring difficult. In Swift, you can use functions and generics to achieve the same results without any compromises.


EDIT
Here is a workaround that I've used before:

In Bridging_Header.h add a wrapper function

    int exposeTestUseDefine2()
    {
        return TEST_USE_DEFINE_2;
    }

main.swift

    print(exposeTestUseDefine2())
  • Related