Cmake (1) - add_subdirectory

1. 專案結構:

建立一個專案結構如下,Cpp, hpp 內容可以參考 Cmake (0) - 簡單 Project。

.
├── CmakeLists.txt
├── build
├── include
│   └── greet.hpp
├── lib
│   ├── CmakeLists.txt
│   └── greet.cpp
└── src
    └── main.cpp

2. 子資料夾中的 CmakeLists.txt:

利用子資料夾中的 CmakeLists.txt 為子資料夾建立處理規則。

.
├── CmakeLists.txt
├── build
├── include
│   └── greet.hpp
├── lib
│   ├── CmakeLists.txt
│   └── greet.cpp
└── src
    └── main.cpp

編輯 lib/CmakeLists.txt,告訴 Cmake 說 Makefile 要把 greet.cpp 編譯成 libgreet。

add_library(greet STATIC greet.cpp)

3. 專案主 CmakeLists.txt:

回到專案外層的主 CmakeLists.txt。

.
├── CmakeLists.txt
├── build
├── include
│   └── greet.hpp
├── lib
│   ├── CmakeLists.txt
│   └── greet.cpp
└── src
    └── main.cpp

編輯 CmakeLists.txt,把 lib 資料夾加入處理清單。

cmake_minimum_required(VERSION 3.11.0)
project(HELLO_CMAKE)

add_subdirectory(lib)
target_include_directories(greet PUBLIC include)

add_executable(main src/main.cpp)
target_link_libraries(main greet)

4. 產生 Makefile and build:

然後就可以生成 Makefile 和 build 執行檔。

$ cd build
$ cmake ..
$ make
$ ./main

留言

熱門文章