教學課程:導出編譯的相依性
在本教學課程中,我們將逐步解說如何使用 vcpkg 導出已編譯的相依性。 當您想要跨多個專案共享連結庫或方便散發時,這特別有用。
必要條件
- Visual Studio 搭配 C++ 開發工作負載和 CMake 元件
- Git
- vcpkg
- 終端機
1 - 安裝 fmt
連結庫
開啟終端機並瀏覽至安裝 vcpkg 的目錄,然後安裝目標平台的連結 fmt
庫:
vcpkg install fmt:x64-windows
以您的目標三重組取代 x64-windows
。
2 - 匯出連結 fmt
庫
安裝 fmt
之後,請執行下列命令來匯出:
vcpkg export fmt:x64-windows --zip
您應該會看到如下輸出:
The following packages are already built and will be exported:
fmt:x64-windows
* vcpkg-cmake:x64-windows
* vcpkg-cmake-config:x64-windows
Additional packages (*) need to be exported to complete this operation.
Exporting vcpkg-cmake:x64-windows...
Exporting vcpkg-cmake-config:x64-windows...
Exporting fmt:x64-windows...
Creating zip archive...
Zip archive exported at: C:\dev\vcpkg\vcpkg-export-20231106-164550.zip
To use exported libraries in CMake projects, add -DCMAKE_TOOLCHAIN_FILE=[...]/scripts/buildsystems/vcpkg.cmake to your CMake command line.
命令會建立 zip 封存,其中包含使用 fmt
連結庫的所有必要檔案,包括二進位檔和標頭。 如需所有支援格式的清單,請參閱 export
命令檔。
3 - 在新的 CMake 專案中使用連結 fmt
庫
若要在新的 CMake 專案中使用連結 fmt
庫,請遵循下列步驟:
將導出的封存解壓縮到您電腦上的已知位置。
為您的 CMake 專案建立新的目錄,並流覽至其中。
CMakeLists.txt
使用下列內容建立 :cmake_minimum_required(VERSION 3.10) project(HelloWorld) find_package(fmt CONFIG REQUIRED) add_executable(HelloWorld main.cpp) target_link_libraries(HelloWorld PRIVATE fmt::fmt)
撰寫您的
main.cpp
檔案以包含fmt
並列印 「Hello, World」:#include <fmt/core.h> int main() { fmt::print("Hello, World!\n"); return 0; }
建置專案 - 在您的終端機中,從專案目錄執行:
cmake -B build -S . -DCMAKE_TOOLCHAIN_FILE=<path-to-archive>/scripts/buildsystems/vcpkg.cmake cmake --build build
執行:
..\build\Debug\HelloWorld.exe
後續步驟
就這麼簡單! 您已匯出連結 fmt
庫,並在個別專案中使用它。
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應