LoginSignup
2
3

More than 5 years have passed since last update.

【C++】boost::timerを使おうとしてコンパイルで詰まった話

Last updated at Posted at 2018-07-08

はじめに

諸事情により,C++でタイマー処理を書きたくなった.
環境はMacOSであるため,WINAPIなるものを使うことは出来ません.
さて,どうしましょう?
ということでBoostライブラリを利用したが,コンパイルで詰まったので個人的にメモしておく.
(情報・表現の正確性は保証しません)

Let's Boost!

「Boost (ブースト)とは、C++の先駆的な開発者のコミュニティ、およびそのコミュニティによって公開されているオープンソースライブラリのことを指す。」 (Wikipediaより引用)
研究でBoostライブラリに依存した某シミュレータを使っている関係上,真っ先にBoostライブラリが思い付いた.
調べたらやっぱりタイマー処理が良い感じに出来るみたいなので使っていきましょう.

Boostのインストール

brew install boost

インストールしたらPATHを通さなきゃいけないみたい.
.bash_profileに以下の内容を追記する.

export PATH=$PATH:/usr/local/Cellar/boost/1.65.1_1/include
export PATH=$PATH:/usr/local/Cellar/boost/1.65.1_1/lib

Homebrew使って入れたなら/usr/local/Cellar/boost/あたりに入っていると思うので適宜書き換えてください.
見つからなかったらsudo find / -name '*boost*'とでも打って検索すれば良いんじゃないですかね?

実行してみる

とりあえず動作確認してみる.
コードは https://boostjp.github.io/tips/timer.html から引用しました

timer.cpp
#include <iostream>
#include <cmath>
#include <boost/timer/timer.hpp>

int main()
{
    boost::timer::cpu_timer timer; // 時間計測を開始

    for (long i = 0; i < 100000000; ++i) {
        std::sqrt(123.456L); // 時間のかかる処理
    }

    std::string result = timer.format(); // 結果文字列を取得する
    std::cout << result << std::endl;
}

実行結果は以下の通り.

$ g++ timer.cpp
Undefined symbols for architecture x86_64:
  "boost::timer::auto_cpu_timer::auto_cpu_timer(short)", referenced from:
      _main in timer-4497dd.o
  "boost::timer::auto_cpu_timer::~auto_cpu_timer()", referenced from:
      _main in timer-4497dd.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation

コンパイルエラーです.困った. (wscriptが予め入っていて./wafでよしなにやってくれる某シミュレータとは勝手が違いますね......)
ということで調べてみると,私と同じところで詰まった人がいたみたい.
https://stackoverflow.com/questions/10565117/undefined-reference-to-boosttimerauto-cpu-timer

要するに-lboost_timerって書いてboost_timerへリンクしてあげないといけないみたいです.
ということで以下のようにして実行

$ g++ timer.cpp -lboost_timer
$ ./a.out
 0.323706s wall, 0.320000s user + 0.000000s system = 0.320000s CPU (98.9%)

ちゃんと動いた.めでたしめでたし.

Boostで他の機能を使う場合に-lboost_systemとか書く場合もあるらしい.
あとBoost.Pythonを使うときには-lboost_pythonとか書く.
とりあえずPATH通してても動かなかったら -lboost_<name>みたいなコンパイルオプション調べれば良さそう?

2
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3