Mac Xcode配置boost庫編寫C++程序

安裝boost

這裏先確保boost庫安裝成功,能正常使用。

Mac下安裝boost庫有兩種方式,編譯源碼homebrew
不知什麼原因,手動編譯源碼失敗:

...failed darwin.compile.c++ 
...failed updating 432 targets... 
...skipped 334 targets... 
...updated 31 targets... 

所以推薦使用homebrew的方式,include文件、lib文件一步到位:

brew install boost 

默認安裝位置是/usr/local/Cellar/boost/1.72.0

驗證boost

下面測試boost環境是否正確搭建。

新建一個xcode命令行項目,點項目文件進入配置頁面:
點項目文件進入配置頁面
在header search paths裏添加/usr/local/Cellar/boost/1.72.0/include
在這裏插入圖片描述

不包含庫的例子

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;
}

編譯通過,代碼已經可以運行了。

包含庫的例子

上面例子中,僅僅指定了頭文件路徑即可。但也有一部分需要依賴指定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;
    }
}

需要在Build Setings - Other linker flags 添加 /usr/local/Cellar/boost/1.72.0/lib/libboost_regex.a
/usr/local/Cellar/boost/1.72.0/lib/libboost_regex.a
即可編譯通過。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章