With the Android NDK Google lets us write C/C++ code for Android. I don’t like writing C/C++ code because it’s error-prone but sometimes there’s no other way.
Unfortunately (this is the “I don’t like this” part), debugging Android C/C++ code is terribly difficult. If you don’t have a week to get the debugging toolchain working, and if you only need some quick and temporary solution, logging may be an alternative.
The easiest form of logging I can think of is using printf()
. Unfortunately, I couldn’t get this working.
Fortunately, the Android NDK provides a logging API for C/C++. Here’s an example:
#include <android/log.h> #define LOG_TAG "testjni" #define ALOG(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) void myMethod() { ALOG("This message comes from C at line %d.", __LINE__); }
ALOG
works like printf()
, so you can add parameters to the log message. The log message is routed to Android’s logcat and has log level “info” (due to ANDROID_LOG_INFO
). The log tag (LOG_TAG
) can be chosen freely.
The last thing you need to do is adding the logging library to your Android.mk
makefile:
include $(CLEAR_VARS) ... LOCAL_LDLIBS := -llog ... include $(BUILD_SHARED_LIBRARY)
Great tip. How come it’s not the first thing you read
Quick question though. How do I log an integer value. I tried
int myint = 5;
ALOG(myint + “This message comes from C++ at line “, __LINE__);
But doesn’t seem to work. any idea?
This doesn’t work in C++. I’m not C guru but I faintly remember a function called “sprintf()” doing this stuff.
Use %d to insert the integer value into the string (just like printf):
ALOG(โ%d This message comes from C++ at line %dโ,__LINE__);
Can you tell me the location of Android.mk file ?
Your post save my life
“I donโt like writing C/C++ code because itโs error-prone but sometimes thereโs no other way” ….. Ahhahahah