2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

cmakeで複数階層フォルダを扱う

Last updated at Posted at 2020-11-21

はじめに

cmakeで複数フォルダそれぞれにCMakeList.txtを置いてmakeする方法は巷にあふれているが、
さらにその階層を何段にも重ねていくときにどう書けば良いのかわからなかったのでまとめる。

例えば以下のような例。

---/
 |--CMakeLists.txt
 |
 |--src/
 |  |--CMakeLists.txt
 |  |--a.cpp
 |  |--lib/
 |     |--CMakeLists.txt
 |     |--b.cpp
 |
 |--test/
 |  |--test.cpp

実装

以下のように記述すればOK。

/CMakeList.txt

add_subdirectory(a)
add_executable(main
./test/test.cpp
)
target_link_libraries(test a b)

/src/CMakeList.txt

add_dependencies(a b)を入れておかないと依存関係がおかしくなるケースがある。

add_subdirectory(b)
add_library(a a.cpp)
add_dependencies(a b)

/src/lib/CMakeList.txt

add_library(b b.cpp)

下の階層のライブラリを一つにまとめたいとき

おそらくこの方法が最もシンプル。

/CMakeList.txt

add_subdirectory(a)
add_executable(main
./test/test.cpp
)
target_link_libraries(test c)

/src/CMakeList.txt

add_subdirectory(b)
add_library(a a.cpp)
add_library(c SHARED $<TARGET_OBJECTS:a>
                     $<TARGET_OBJECTS:b>)
                                

/src/lib/CMakeList.txt

変更なし。

補足:Macで動的ライブラリを作成するとき

Macでは動的ライブラリを作成するとき、未定義シンボルがあると弾かれる。
それを回避するには、cmakeに以下の記述を追加する。

set(CMAKE_CXX_FLAGS "-dynamic -undefined dynamic_lookup -Qunused-arguments")
set(CMAKE_C_FLAGS "-dynamic -undefined dynamic_lookup -Qunused-arguments")
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?