Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access $(TARGET_ARCH) from C++ file?

Using the Android NDK I'd like to know which target architecture is active when executing pre-processor code in my C++ header files. For example, my code would behave differently on "armeabi" vs. "armv7".

The $(TARGET_ARCH) variable can be used within makefiles, but is there an equivalent that's accessible from within C++ headers?

Thanks.

like image 268
Bungles Avatar asked Feb 05 '23 22:02

Bungles


2 Answers

In addition to what Dan Albert posted, the hello-jni example actually already shows the necessary ifdefs for detecting the different ABIs:

https://github.com/googlesamples/android-ndk/blob/master/hello-jni/app/src/main/cpp/hello-jni.c

#if defined(__arm__)
    #if defined(__ARM_ARCH_7A__)
    #if defined(__ARM_NEON__)
      #if defined(__ARM_PCS_VFP)
        #define ABI "armeabi-v7a/NEON (hard-float)"
      #else
        #define ABI "armeabi-v7a/NEON"
      #endif
    #else
      #if defined(__ARM_PCS_VFP)
        #define ABI "armeabi-v7a (hard-float)"
      #else
        #define ABI "armeabi-v7a"
      #endif
    #endif
  #else
   #define ABI "armeabi"
  #endif
#elif defined(__i386__)
#define ABI "x86"
#elif defined(__x86_64__)
#define ABI "x86_64"
#elif defined(__mips64)  /* mips64el-* toolchain defines __mips__ too */
#define ABI "mips64"
#elif defined(__mips__)
#define ABI "mips"
#elif defined(__aarch64__)
#define ABI "arm64-v8a"
#else
#define ABI "unknown"
#endif
like image 97
mstorsjo Avatar answered Feb 15 '23 12:02

mstorsjo


I've found the below Wiki to be really useful for looking up built-in preprocessor definitions:

Pre-defined Compiler Macros

Scrolling down the the section for ARM, you can see that ARM 7 will have:

__ARM_ARCH_7__

or a handful of other variants of ARM 7. Looks like there's also _M_ARM, which will be 7 for any of the variants.

Another way to check this sort of thing is to dump all of the predefined macros that the compiler will provide like so:

$ clang -dM -E - < /dev/null

You can then look through all the different preprocessor defines until you find what you're looking for.

If you wanted to access the exact string that is TARGET_ARCH from C++, you could do the following in your Android.mk (as part of the module definition):

LOCAL_CFLAGS += -DTARGET_ARCH="$(TARGET_ARCH)"
like image 38
Dan Albert Avatar answered Feb 15 '23 14:02

Dan Albert