必要條件
本教學課程以編譯 FIDL 教學課程為基礎。如需完整的 FIDL 教學課程,請參閱總覽。
簡介
本教學課程逐步說明如何使用 fostr
工具,為 HLCPP 類型新增偵錯列印功能。
如果您要自行編寫程式碼,請刪除下列目錄:
rm -r examples/fidl/hlcpp/fostr farnet/public/lib/fostr/fidl
本教學課程包含下列步驟:
- 為 FIDL 程式庫定義
fostr_fidl
目標。如此一來,只要為每個類型定義operator<<
,就能允許程式庫中的類型的偵錯列印。 - 使用
fostr_fidl
目標。 - 使用格式設定工具程式碼編寫範例。
定義 fostr_fidl 目標
在
//src/lib/fostr/fidl
中為 BUILD 檔案建立目錄:mkdir -p src/lib/fostr/fidl/fuchsia.examples
建立 BUILD 檔案:
touch src/lib/fostr/fidl/fuchsia.examples/BUILD.gn
在建構檔案中加入下列定義:
# Copyright 2020 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import("//src/lib/fostr/build/fostr_fidl.gni") fostr_fidl("fuchsia.examples") { fidl_target = "//examples/fidl/fuchsia.examples" }
這會定義 fuchsia.examples
程式庫的 fostr
目標。程式庫的任何依附元件也必須在建構檔案中指定。由於其沒有依附元件,因此不適用於本教學課程。如需更複雜的範例,請參閱 fostr fidl
目錄中的現有定義。
新增 fostr_fidl 目標的依附元件
本教學課程使用的目標程式庫是簡單的主機測試,位於 examples/fidl/hlcpp/fostr
中。請注意,測試的 BUILD 檔案會包含 fostr_fidl
目標做為依附元件:
executable("bin") {
testonly = true
output_name = "fostr_example_test"
sources = [ "main.cc" ]
deps = [
"//examples/fidl/fuchsia.examples:fuchsia.examples_hlcpp",
"//src/lib/fostr/fidl/fuchsia.examples",
"//src/lib/fxl/test:gtest_main",
]
}
包含的程式庫會自動超載 <<
運算子。該路徑是以針對下列項目產生的 FIDL 程式庫名稱為準:
#include <src/lib/fostr/fidl/fuchsia/examples/formatting.h>
使用格式設定工具程式碼編寫範例
撰寫一些預留位置測試來展現輸出內容:
TEST(FidlExamples, Bits) {
auto flags = fuchsia::examples::FileMode::READ | fuchsia::examples::FileMode::WRITE;
std::cout << flags << std::endl;
}
TEST(FidlExamples, Enums) {
auto enum_val = fuchsia::examples::LocationType::MUSEUM;
std::cout << enum_val << std::endl;
}
TEST(FidlExamples, Structs) {
fuchsia::examples::Color default_color;
std::cout << default_color << std::endl;
}
TEST(FidlExamples, Unions) {
auto int_val = fuchsia::examples::JsonValue::WithIntValue(1);
std::cout << int_val << std::endl;
}
執行範例
如要執行範例:
設定 GN 版本以加入範例:
fx set core.x64 --with //examples/fidl/hlcpp/fostr
執行測試:
fx test -vo fostr-example-test