2011-03-28 154 views
1

在调试我的本地代码我写这几行:如何在gdb中查看printf行?

m_sock = socket(m_iAf, m_iType, m_iProtocol); 
printf("errno = %d, %s\n", errno, strerror(errno)); 
printf("Hellowrold\n"); 

我创建了一个插座,但是当我执行这一行,它返回负。 所以我必须找到错误。但控制台上不显示errno和Helloworld的打印。

如何查看打印的行?

我是新的ndk-gdb,所以需要帮助。

感谢, Riasat

回答

11

代替了printf,你可以使用android日志记录功能:

#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"); 

不用了,尾随“\ n”在这里,这些将显示在logcat中。您还需要链接到日志记录库。在你的Android.mk文件中添加以下内容:

LOCAL_LDLIBS := -llog 
+0

@StarDust添加了一个编辑 - 您必须明确链接到日志记录库。 – richq 2011-04-13 11:36:59

+0

我只是添加#define选项来覆盖'printf' __android_log_print' – Zaffy 2012-09-26 14:10:22

+0

谢谢!你从字面上挽救了我的一天。 :) – conciliator 2013-11-20 12:14:32

1

只需拨打字符串错误从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" 

(对我来说,通常在第一次调用的作品,这是我见过这个错误第一次,因此我将它包括在内以保证完整性。)

对于查看输出的一般问题,通常在运行程序时通过重定向将程序的输出与gdb的输出分开是最容易的。例如,有一个“尾巴-f输出文件”一个终端打开,然后做:

 
(gdb) run > output-file 
1

试试这个方法。 Android cpp源以这种方式打印日志。

#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. 

上面的代码将在logcat中用红色打印错误日志。

您还可以使用

  • LOGW - 警告
  • LOGD - 调试
  • LOGI - 资讯
  • LOGV - 详细
+0

在较新版本的Android(例如Kitkat(4.4.2))中,似乎''被替换为''。 'LOGx'被'ALOGx'替代 – gfrigon 2015-03-31 01:07:40

0

有更短的宏可用以登录到logcat。这个例子工程奇巧(4.4.2)

#define LOG_TAG "my_log_tag" 
#include <cutils/log.h> 

ALOGD("Format this %d, some_int); 

在Android.mk中,liblog图书馆建设 'mydroid'(全Android系统版本)时增加LOCAL_SHARED_LIBRARIES。如果使用ndk编译LOCAL_LDLIBS:= -L $(SYSROOT)/ usr/lib -llog可以使用。

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) 

还有其他各种为所有级别的日志定义的宏。从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__))