https://github.com/stephane/libmodbus
在上面的地址下載庫。
然後安裝以下工具:
sudo apt-get install autoconf
sudo apt-get install automake
sudo apt-get install libtool
把安裝包解壓到某目錄下,cd 到此目錄
cd ~/libmodbus-master
運行
./autogen.sh
生成腳本configure
./configure && make install //可能權限不夠,在前面加sudo
顯示
----------------------------------------------------------------------
Libraries have been installed in:
/usr/local/lib
If you ever happen to want to link against installed libraries
in a given directory, LIBDIR, you must either use libtool, and
specify the full pathname of the library, or use the '-LLIBDIR'
flag during linking and do at least one of the following:
- add LIBDIR to the 'LD_LIBRARY_PATH' environment variable
during execution
- add LIBDIR to the 'LD_RUN_PATH' environment variable
during linking
- use the '-Wl,-rpath -Wl,LIBDIR' linker flag
- have your system administrator add LIBDIR to '/etc/ld.so.conf'
See any operating system documentation about shared libraries for
more information, such as the ld(1) and ld.so(8) manual pages.
----------------------------------------------------------------------
安裝完成,測試:在libmodbus-master下運行
make check
顯示
============================================================================
Testsuite summary for libmodbus 3.1.4
============================================================================
# TOTAL: 1
# PASS: 1
# SKIP: 0
# XFAIL: 0
# FAIL: 0
# XPASS: 0
# ERROR: 0
============================================================================
在兩個終端分別運行以下測試程序
cd ~/libmodbus-master/tests
./unit-test-server
cd ~/libmodbus-master/tests
./unit-test-client
可以看到兩端的輸入輸出,配置成功。
官方提示我們可以用pkg-config.查了一下:
庫文件編譯完成後,會在{installed_home/lib/}下生成產生一個名爲pkgconfig的目錄,內含該鏈接庫的.pc文件,此文件記錄了改庫的相關信息。爲了能被查找讀取到,需要將該.pc文件安裝到 /usr/lib/pkgconfig/ 目錄中,或在PKG_CONFIG_PATH環境變量中加入該.pc文件的安裝路徑。這樣做的目的是爲了使依賴此庫的其它程序能夠藉助pkg-config自動鏈接該庫,避免編譯期錯誤。
然後在文件夾中可以看到libmodbus.pc,把此文件夾加入到pkg-config的搜索範圍,參考如下:
export PKG_CONFIG_PATH=/home/wxw/libmodbus-master/
查看PKG PATH
echo $PKG_CONFIG_PATH
然後檢查下能不能查到
$ pkg-config --cflags libmodbus
-I/usr/local/include/modbus
$ pkg-config --libs libmodbus
-L/usr/local/lib -lmodbus
–-list-all 列出所有已安裝的共享庫
-–cflags 列出指定共享庫的預處理和編譯flag。
-–libs 列出指定共享庫的鏈接flag。
之後使用libmodbus庫時,就可以這麼寫:
$ gcc sample.c -o sample `pkg-config --cflags --libs libmodbus`
g++ main.cpp robot_modbus.cpp -o modrobot `pkg-config –libs libmodbus`
使用 pkg-config 的 –cflags 參數可以給出在編譯時所需要的選項,而 –libs 參數可以給出連接時的選項。例如,假設一個 sample.c 的程序用到了libmods庫,就可以這樣編譯:
$ gcc -c `pkg-config –cflags libmods` sample.c
然後這樣連接:
$ gcc sample.o -o sample `pkg-config –libs libmods`