ndk icon indicating copy to clipboard operation
ndk copied to clipboard

investigate using `#pragma comment(lib, ...)`

Open DanAlbert opened this issue 2 years ago • 0 comments

We just found a pretty big landmine with this feature. In the example we just encountered this on:

if (__builtin_available(android 29, *)) {
  ATrace_beginAsyncSection("ndk::asyncBeginEndSection", 0);
}

The code is right. It includes a check for __builtin_available to make sure the app is running on a new enough version of the OS before making the maybe-available API call.

The part that was wrong isn't visible here (and therefore isn't visible to the compiler, so it can't diagnose this): the build script forgot to link libandroid. The loader saw the weak symbol, couldn't find a definition for it, and set ATrace_beginAsyncSection to nullptr. __builtin_available returned true though, because the device we were running on was API 32, so the call segfaulted.

Could you add a #pragma comment(lib, "android") in the relevant headers so that including the header also ensures that you link against the library? That started out as a Windows thing, but Clang and LLD have supported it for ELF for a while now, and I believe e.g. Fuchsia uses it pretty extensively. I guess it'd still need to be guarded by an __ANDROID_API__ check for libraries which were introduced in later API levels, so it's not foolproof, but it's still something.

Originally posted by @smeenai in https://github.com/android/ndk/issues/837#issuecomment-1718722941

DanAlbert avatar Sep 14 '23 19:09 DanAlbert