1

What is the correct way to check at runtime if a C function exists or not?

This documentation page says that you should check this using if (MyWeakLinkedFunction != NULL), but this sample code says that you should use if (&UIApplicationOpenSettingsURLString == NULL) {.

I currently need this for SecAddSharedWebCredential and UIApplicationOpenSettingsURLString.

With a deployment target of iOS 7.0, it throws no warning neither for the first function nor for the second one, not matter if I add or not the &.

With a deployment target of iOS 8.0 and with & added for both, UIApplicationOpenSettingsURLString throws the warning:

Comparison of address of 'UIApplicationOpenSettingsURLString' not equal to a null pointer is always true

Removing the & from both function checks, SecAddSharedWebCredential throws the warning:

Comparison of function 'SecAddSharedWebCredential' not equal to a null pointer is always true

Why aren't both throwing the same warning if both are available since iOS 8.0? And what is the correct way to check this, disregarding the warnings?

Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113

2 Answers2

1

For functions, the & is optional. For other types, such as a dictionary key, it is necessary.

This is because the use of a function symbol in an expression is automatically converted to a pointer to the function. Try reading the answers to question Function pointers and address of a function.

Maybe an example will illustrate this:

extern int functionA(void);
extern NSString * const valueA;

// ...
printf("%p <-  functionA\n", functionA);
printf("%p <- &functionA\n", &functionA);
printf("%p <-  valueA\n", valueA);
printf("%p <- &valueA\n", &valueA);

Will output something similar to:

0x1089a8f00 <-  functionA
0x1089a8f00 <- &functionA
0x1089a9018 <-  valueA
0x1089a9040 <- &valueA

The third line will crash if valueA is not available at runtime.

Community
  • 1
  • 1
Mats
  • 8,528
  • 1
  • 29
  • 35
0

Having to check for NULL is required only if you deployment target is less than 8.0, otherwise it is not NULL - thats what the warnings state. Both of those were added in iOS 8.0, so if your deployment target is iOS 8.0 and up you don't need to check for NULL.

Mindaugas
  • 1,707
  • 13
  • 20