2011-03-28 153 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__))