Cygwin+Clang+CMake

前提

  1. gcc+make等がインストール済み
  2. CMakeがインストール済み

clang+llvmをインストール

$ apt-cyg install clang
$ apt-cyg install llvm

Clangは標準ライブラリのinclude先がビルド時に決まってしまうのだが、パッケージで提供されているClangのバイナリと手元のGCCライブラリのバージョンが違う事があるようだ。

$ clang++ -print-search-dirs

上記のコマンドを叩いて、出てくるPathは僕の場合は以下のようになった。

$ clang++ -print-search-dirs
programs: =/usr/bin
libraries: =/usr/bin/../lib/clang/3.1:/usr/lib/gcc/i686-pc-cygwin/4.5.3:/usr/lib

だが僕の環境に入っているのは「/usr/lib/gcc/i686-pc-cygwin/4.7.3」なのでコンパイルが通らない。
このままコンパイルしてみると、以下のようにiostream無いと怒られる。

$ clang++ main.cpp -S -emit-llvm -o a.out.bc
main.cpp:3:10: fatal error: 'iostream' file not found
#include <iostream>
         ^
1 error generated.

仕方ないので「/usr/lib/gcc/i686-pc-cygwin/4.7.3」を丸ごとコピーして、「/usr/lib/gcc/i686-pc-cygwin/4.5.3」にリネームする事で、一応コンパイルは通った。

CMake用のToolChainファイルを作る

CMakeは環境用のファイルとしてToolChainFileと言う物を使う事を推奨している。
なので、以下の様なファイルを用意してCMakeに指定する

# which compilers to use for C and C++
find_program(CMAKE_C_COMPILER   NAMES clang)
find_program(CMAKE_CXX_COMPILER NAMES clang++)
find_program(CMAKE_LINKER       NAMES llvm-ld)
find_program(CMAKE_RANLIB       NAMES llvm-ranlib)
find_program(CMAKE_AR           NAMES llvm-ar)

使い方はCMakeLists.txtの存在するディレクトリで以下のコマンドを実行する。

$ cmake -DCMAKE_TOOLCHAIN_FILE=CMakeTiikChain-clang32.cmake .

あとはMake.

CMakeのVersionによっては以下の様なWarningが出る

$ cmake -DCMAKE_TOOLCHAIN_FILE=CMakeToolChain-clang32.cmake
CMake Warning at /usr/share/cmake-2.8.9/Modules/Platform/CYGWIN.cmake:15 (message):
  CMake no longer defines WIN32 on Cygwin!

  (1) If you are just trying to build this project, ignore this warning or
  quiet it by setting CMAKE_LEGACY_CYGWIN_WIN32=0 in your environment or in
  the CMake cache.  If later configuration or build errors occur then this
  project may have been written under the assumption that Cygwin is WIN32.
  In that case, set CMAKE_LEGACY_CYGWIN_WIN32=1 instead.

  (2) If you are developing this project, add the line

    set(CMAKE_LEGACY_CYGWIN_WIN32 0) # Remove when CMake >= 2.8.4 is required

  at the top of your top-level CMakeLists.txt file or set the minimum
  required version of CMake to 2.8.4 or higher.  Then teach your project to
  build on Cygwin without WIN32.

その場合はCMakeLists.txtに以下を追加する。
もちろん2.8.4以前では動かなくなるので注意。

cmake_minimum_required (VERSION 2.8.4)