LoginSignup
7
5

More than 5 years have passed since last update.

CMake で Boost を静的リンクする

Posted at

CMake で Boost を静的リンクする

CMake では静的リンクするために対象のファイルそれぞれに add_libraryset_target_properties という前準備が必要。
なんだけど、 Boost のようにたくさんあるものをひとつひとつ対処するのもなぁ、ということでスクリプトを書いてみた。

generate-boost-static-settings.rb
#!/usr/bin/env ruby

#
# generate-boost-static-settings.rb
#
#   ./generate-boost-static-settings.rb > boost-static.cmake
#

CMAKE_VERSION = 2.8
LIB_PATH = '/usr/local/lib'
CMAKE_TEMPLATE = <<EOS
# ${libname}
add_library(boost_${libname}_static
    STATIC
    IMPORTED
)

set_target_properties(boost_${libname}_static
    PROPERTIES
    IMPORTED_LOCATION #{LIB_PATH}/libboost_${libname}.a
)

EOS

puts "cmake_minimum_required(VERSION #{CMAKE_VERSION})"
puts

Dir.glob(LIB_PATH + '/*') {|file|
    if matched = /libboost_(\w+)\.a/.match(file)
        libname = matched[1]
        puts CMAKE_TEMPLATE.gsub(/\$\{libname\}/, libname)
    end
}

LIB_PATH は適宜書き換えておくんなさい。
これを実行すると次のような出力になるのでファイルに保存してプロジェクトルートの CMakeLists.txt から include とか、直接 CMakeLists.txt に書くとかしてください。

cmake_minimum_required(VERSION 2.8)

# atomic
add_library(boost_atomic_static
    STATIC
    IMPORTED
    )

set_target_properties(boost_atomic_static
    PROPERTIES
    IMPORTED_LOCATION /usr/local/lib/libboost_atomic.a
    )

#
# snip
#

# unit_test_framework
add_library(boost_unit_test_framework_static
    STATIC
    IMPORTED
    )

set_target_properties(boost_unit_test_framework_static
    PROPERTIES
    IMPORTED_LOCATION /usr/local/lib/libboost_unit_test_framework.a
    )

リンク指定する際は普通に target_link_librariesboost_<target>_static を指定するだけ。 Boost Filesystem を静的リンクしたい場合は次のように。

# filesystem
add_library(boost_filesystem_static
    STATIC
    IMPORTED
    )

set_target_properties(boost_filesystem_static
    PROPERTIES
    IMPORTED_LOCATION /usr/local/lib/libboost_filesystem.a
    )

add_executable(my-command
    main.cpp
    )

target_link_libraries(my-command
    boost_filesystem_static
    )
7
5
0

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
7
5