macOS 中Boost的安裝和使用


1 安裝Boost

1.1 使用源碼安裝

  1. 下載Boost源碼
  2. 解壓放在任意目錄,例如/home/wang/
  3. ./bootstrap.sh,默認的位置是在usr/local下面;可以通過--prefix="絕對路徑"來指定
  4. ./b2 install
  5. 留意運行日志頭文件目錄 /usr/local/include, lib目錄/usr/local/lib

打開源碼中index.html查看使用文檔

1.2 使用Homebrew安裝

  1. 下載安裝HomeBrew
  2. brew install boost
  3. 留意運行日志會顯示頭文件目錄 /usr/local/Cellar/boost/1.60.0_2/include, lib目錄/usr/local/Cellar/boost/1.60.0_2/lib

1.3 使用MacPort安裝

  1. 下載安裝MacPort
  2. sudo port install boost

2. 在XCode項目中使用Boost

  1. 新建一個Command Line Tool項目
  2. 在Build Setings - Header Search Paths 增加頭文件目錄
  3. 替換main.cpp中代碼,運行!輸入任意數字回車可看到結果。
#include <iostream>
#include <boost/lambda/lambda.hpp>

int main(int argc, const char * argv[]) {
  
    printf("Please input any number:");
  
    using namespace boost::lambda;
  
    typedef std::istream_iterator<int> in;

    std::for_each(
                  in(std::cin), in(), std::cout << (_1 * 3) << " " );

    return 0;
}

3. 在XCode項目中使用Boost Lib庫

Boost的很多功能都是直接在hpp頭文件里實現的,比如上面的lambda例子不用導入任何lib就可以運行了。但也有一部分需要依賴指定lib庫才能使用。比如下面這個正則表達式的例子:

#include <iostream>

#include <boost/regex.hpp>

int main(int argc, const char * argv[]) {
  
    std::string   str = "2013-08-15";

    boost::regex  rex("(?<year>[0-9]{4}).*(?<month>[0-9]{2}).*(?<day>[0-9]{2})");

    boost::smatch res;

    std::string::const_iterator begin = str.begin();

    std::string::const_iterator end   = str.end();

    if (boost::regex_search(begin, end, res, rex))

    {
     	  std::cout << "Day:   " << res ["day"] << std::endl
        << "Month: " << res ["month"] << std::endl
        << "Year:  " << res ["year"] << std::endl;
    }
}

3.1 使用靜態庫

在Build Setings - Other linker flags /usr/local/boost_1_63_0/stage/lib/libboost_regex.a

使用命令行編譯相當於

c++ -I /usr/local/boost_1_63_0 main.cpp -o main /usr/local/boost_1_63_0/stage/lib/libboost_regex.a
./main

如果這里直接使用lboost_regex, Xcode默認加載動態庫。實際運用中可以考慮將目錄中的動態庫刪除,只保留靜態庫,並在Build Setings - Library Search Paths 增加lib文件目錄。

3.2 使用動態庫

  1. 在Build Setings - Library Search Paths 增加lib文件目錄
  2. 將lib文件目錄中的libboost_regex.dylib文件拖入項目
  3. 確保在Build Phases - Link Bindary With Libraries中已經有該庫
  4. 在Build Phases - Copy Files, 復制libboost_regex.dylib到Products Directory

使用命令行編譯相當於

c++ -I /usr/local/boost_1_63_0 main.cpp -o main -L/usr/local/boost_1_63_0/stage/lib/ -lboost_regex
cp /usr/local/boost_1_63_0/stage/lib/libboost_regex.dylib ./
./main


免責聲明!

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



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