Boost.asio入門心得: 編譯和鏈接的注意事項


  最近准備跟樂搞個IM. 網絡這個坑終究還是准備想跳了, 於是拿來Boost.asio小試牛刀. 折騰了幾天, 也遇到了不少問題.  參考資料: Boost官方文檔. 

  Boost中大部分庫包含hpp文件即可直接使用, 少部分需要預先編譯. asio這個庫依賴了幾個需要編譯的庫: system, regex, date_time, serialization, thread. 所以, 要使用asio, 首先要編譯這幾個庫. 如官方文檔所說(http://www.boost.org/doc/libs/1_41_0/doc/html/boost_asio/using.html#boost_asio.using.building_boost_libraries):

  You may build the subset of Boost libraries required to use Boost.Asio and its examples by running the following command from the root of the Boost download package:

bjam --with-system --with-thread --with-date_time --with-regex --with-serialization stage

  具體bjam的編譯選項可以參考bjam的相關文檔. 或者直接使用bjam --help也可以看到bjam的各種參數的說明. 這里不再贅述. 

  編譯好之后, 照着tutorial, 拉下來兩份代碼, 分別是Daytime.1和Daytime.2

http://www.boost.org/doc/libs/1_41_0/doc/html/boost_asio/tutorial/tutdaytime1.html

http://www.boost.org/doc/libs/1_41_0/doc/html/boost_asio/tutorial/tutdaytime2.html

  文檔里面對代碼幾乎每行都有注釋了, 而且結構簡單也不難理解. 但是在編譯的過程中遇到點麻煩.使用gcc(mingw)分別在linux下和windows下進行編譯. 

  lwindows下的makefile如下: 

 
         

all:client.exe server.exe

 
         

client.exe:client.cpp
g++ client.cpp -o client.exe \
  -I D:\workplace\tools\boost_1_49_0 \
  -L D:\workplace\tools\boost_1_49_0\stage\lib \
  -static -lpthread -lboost_thread-mgw44-mt-1_49 \
  -lboost_system-mgw44-mt-1_49 \
  -lboost_date_time-mgw44-mt-1_49 \
  -lboost_regex-mgw44-mt-1_49 \
  -lwsock32 \
  -lws2_32


server.exe:server.cpp
  g++ server.cpp -o server.exe \
  -I D:\workplace\tools\boost_1_49_0 \
  -L D:\workplace\tools\boost_1_49_0\stage\lib \
  -static -lpthread -lboost_thread-mgw44-mt-1_49 \
  -lboost_system-mgw44-mt-1_49 \
  -lboost_date_time-mgw44-mt-1_49 \
  -lboost_regex-mgw44-mt-1_49 \
  -lwsock32 \
  -lws2_32

 

  除了需要鏈接boost_thread, boost_system, boost_date_time, boost_regex之外, 還需要鏈接pthread, wsock32和ws2_32. 在linux下, 就不需要wsock32和ws2_32了. 

  另外關於代碼中的一點說明: 

  在代碼server.cpp中, 

tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 13));

  tutorial中的端口號設置為13. 實際上貌似5000一下的端口號都是系統使用了的. 將這個值設置為一個大於5000的值. 

 

  在代碼client.cpp中, 

tcp::resolver::query query(argv[1], "daytime");

  這一行query構造函數的兩個參數, 分別代表的主機的ip地址和端口號(或服務名稱). 嘛, 看來看去沒看出來server那邊咋知道自己叫做 "daytime" 的. 於是將第二個參數改成server.cpp中設定的端口號的值. 

  編譯成功之后, 首先運行server.exe, 然后運行client.exe, 在命令行參數中輸入server的ip地址. 如果是本機為server的話可以直接使用 "localhost" 或者 "127.0.0.1" , 然后會打印出client從server中獲取的時間. 

  這個看似簡單的過程其實還是不知不覺的折騰了許久. 終於搞定了. 下一步繼續研究下asio的各種基本用法, 研究下example里面的內容. 

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM