go build -ldflags 參數及 gdb 調試

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

go build -ldflags 參數及 gdb 調試

有時發布時我們想隱藏所有代碼實現相關的資訊,使用 go build -ldflags 參數可以實現相關要求。

範例程式碼

本文使用版本為go 1.6。

package mainimport "log"type MyCat struct {    name string    age  int}func main() {    cat := MyCat{        name: "tom",        age:  10,    }    log.SetFlags(log.Llongfile)    log.Println(cat)}

使用-ldflags

設定編譯參數-ldflags "-w -s"
其中-w為去掉調試資訊(無法使用gdb調試),-s為去掉符號表(暫未清楚具體作用)。

go build -ldflags "-w -s" ./hello.go
  1. 運行觀察列印,看見檔案名稱、行號等資訊依然保留。

    ./hello

    列印輸出如下。而且將該可執行檔置於任何目錄下執行,都顯示相同的輸出。
    可見,檔案名稱和行號為編譯時間將當前的檔案名稱和行號編譯進二進位檔案中。

    /home/gv/hello.go:17: {tom 10}
  2. 使用LiteIDE查看二進位檔案可以搜尋到MyCat標識符。

  3. 使用gdb無法調試,可見調試資訊已清除

    gdb ./hello(gdb) l main.mainNo symbol table is loaded.  Use the "file" command.

不使用-ldflags

go build ./hello.go
  1. 運行列印看見檔案名稱、行號。

  2. 使用LiteIDE查看二進位檔案可以搜尋到MyCat標識符。

    上述都與使用 -ldflags 參數得到的結果相同。

  3. 使用gdb調試可列出原始碼,也可打斷點單步調試。

    (gdb) l main.main5   type MyCat struct {6       name string7       age  int8   }910  func main() {11      cat := MyCat{12          name: "tom",13          age:  10,14      }
  4. 將源檔案刪除後再使用gdb調試,可打斷點單步調試,但無法列出原始碼,只能列出行號和檔案名稱。

    gdb ./hello(gdb) l main.main5   /home/gv/hello.go: No such file or directory.    in /home/gv/hello.go

    可見,調試如需列出原始碼還需在其編譯時間寫進的檔案名稱和行號中尋找。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.