How to see printf lines in gdb?
While debug开发者_运维知识库ging my native code I wrote these lines:
m_sock = socket(m_iAf, m_iType, m_iProtocol);
printf("errno = %d, %s\n", errno, strerror(errno));
printf("Hellowrold\n");
I created a socket, but when i execute this line, it's returning negative. So I have to find the error. But the printing of neither errno nor Helloworld is shown on the console.
How can I see the printed lines?
I am new with ndk-gdb, so need help please.
Thanks, Riasat
Instead of printf you can use the android logging facility:
#include <android/log.h>
__android_log_print(ANDROID_LOG_INFO, "MYPROG", "errno = %d, %s", errno, strerror(errno));
__android_log_print(ANDROID_LOG_INFO, "MYPROG", "Hellowrold");
No need for the trailing "\n" here and these will show up in logcat. You need to link to the logging library too. In your Android.mk file, add the following:
LOCAL_LDLIBS := -llog
Just call strerror directly from within gdb:
(gdb) call strerror( errno ) Unable to call function "strerror" at 0x7fff857ae897: no return type information available. To call this function anyway, you can cast the return type explicitly (e.g. 'print (float) fabs (3.0)') (gdb) print (char *) strerror( errno ) $1 = 0x7fff85892565 "Interrupted system call"
(For me, normally the first call works, and this is the first time I've ever seen this error, so I'm including it for completeness.)
For the general question of viewing output, it is typically easiest to just separate the output of the program from gdb's output by redirecting when you run the program. For example, have one terminal open with a 'tail -f output-file' and then do:
(gdb) run > output-file
Try this way. Android cpp source prints log in this way.
#define LOG_TAG "A_TAG" // the tag to be shown in logcat
#include <utils/Log.h>
LOGE("Hello world: %s,%d",__FILE__,__LINE__); // somewhat like printf.
The code above will print a error log with red color in logcat.
You can also use
- LOGW - warning
- LOGD - debug
- LOGI - info
- LOGV - verbose
There are shorter macros available in order to log to logcat. This example works in kitkat (4.4.2)
#define LOG_TAG "my_log_tag"
#include <cutils/log.h>
ALOGD("Format this %d, some_int);
In Android.mk, add the liblog library to LOCAL_SHARED_LIBRARIES when building in 'mydroid' (full android system build). In case of ndk build LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -llog can be used.
include $(CLEAR_VARS)
LOCAL_MODULE := foo
LOCAL_SRC_FILES := foo.c
# if mydroid
LOCAL_SHARED_LIBRARIES := liblog
# in ndk, use LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -llog instead
include $(BUILD_EXECUTABLE)
There are various other macros defined for all levels of logging. From cutils/log.h
:
#define ALOGV(...) ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__))
#define ALOGD(...) ((void)ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__))
...
#define ALOGE(...) ((void)ALOG(LOG_ERROR, LOG_TAG, __VA_ARGS__))
精彩评论