Skip to content

Devel GTK Version specific macro

Simeon Andreev edited this page Feb 23, 2023 · 1 revision

The SWT-GTK development guide talks about making functions dynamic so that they can be used in the SWT code base without causing errors during compilation. This is especially useful when dealing with deprecated functions. While this mechanism works well for functions, there is no equivalent for macros. There are cases where a macro will need to run or "exist" only in a certain version of GTK, namely when a new macro is introduced or an older macro should no longer be defined in newer versions of GTK.

Take, for example, the macro GTK_STOCK_OK(). GTK_STOCK_OK() provides an "OK" icon for buttons. In GTK3.10, stock icons were deprecated. This means defining calling GTK_STOCK_OK() in GTK3.10+ will generate a deprecation warning (which is not desirable).

GTK_STOCK_OK() is defined in OS.java as such:

 /** @method flags=const */
 public static final native long /*int*/ _GTK_STOCK_OK();
 public static final long /*int*/ GTK_STOCK_OK() {
         lock.lock();
     try {
                 return _GTK_STOCK_OK();
         } finally {
                 lock.unlock();
         }
 }

By default, this create a generated entry in os.c:

 #ifndef NO__1GTK_1STOCK_1OK
 JNIEXPORT jintLong JNICALL OS_NATIVE(_1GTK_1STOCK_1OK)
         (JNIEnv *env, jclass that)
 {
         jintLong rc = 0;`
         OS_NATIVE_ENTER(env, that, _1GTK_1STOC_1OK_FUNC);
         rc = (jintLong)GTK_STOCK_OK;
         OS_NATIVE_EXIT(env, that, _1GTK_1STOCK_1OK_FUNC);
         return rc;
 }
 #endif

Initially, this macro will always be compiled, regardless of what version of GTK is being used. This may cause warnings/errors if this macro has been deprecated or removed from GTK. In order to prevent this, you can specify a version guard in os_custom.h. This allows you to specify a version range for which this macro should be defined. For example, in this case we only want GTK_STOCK_OK() to compile for GTK2. The entry in os_custom.h would read as follows. Notice we copy the function signature/name from os.c, not from OS.java:

 #if GTK_CHECK_VERSION(3,0,0)
 #define NO__1GTK_1STOCK_1CANCEL
 #define NO__1GTK_1STOCK_1OK
 #endif

This means for GTK3 and up, GTK_STOCK_OK() will be defined as null. Different combinations of #ifndef or #if !GTK_CHECK_VERSION(x,x,x) can be used to achieve different results. You can browse through os_custom.h and see other examples for reference. Specific major, minor, and micro versions of GTK can also be specified: for example, if you wanted only GTK3.14.2, you could use GTK_CHECK_VERSION(3,14,2).

Clone this wiki locally