From 0690d6d751e3dc800d24bb7ebecbe67c9cdf4680 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andrzej=20Warzy=C5=84ski?= Date: Sat, 7 Dec 2024 11:39:39 +0000 Subject: [PATCH] Add examples with LLVM's StringRef Also adds LLVM's libLLVMSUpport as a dependency. --- CMakeLists.txt | 6 +++++- src/strings_1_main.cpp | 10 ++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 29344f1..5c8beb5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -235,6 +235,10 @@ target_compile_options(${executable} PRIVATE "$<$:${cpp-tutor_COMPILER_OPTIONS_MSVC}>") endforeach() +target_link_libraries(strings_1 + LLVMSupport +) + # EXTRA SET-UP FOR UNIT TESTS # =========================== @@ -258,4 +262,4 @@ option(RUNTIME_ERROR "Enable code that leads to run-time errors (e.g. UB)." OFF) configure_file( ${PROJECT_SOURCE_DIR}/include/cppt_ag.hpp.in ${PROJECT_BINARY_DIR}/include/cppt_ag.hpp - ) +) diff --git a/src/strings_1_main.cpp b/src/strings_1_main.cpp index 75c06b9..5019706 100644 --- a/src/strings_1_main.cpp +++ b/src/strings_1_main.cpp @@ -17,6 +17,9 @@ #include #include +#include "llvm/Support/raw_ostream.h" +#include + #include #include #include @@ -37,6 +40,7 @@ int main(int argc, const char** argv) { const char* hello_c_c = "Hello World!"; std::string hello_cpp(hello_c); std::string_view hello_sv(hello_cpp); + llvm::StringRef hello_sr(hello_cpp); //------------------------------------------------------------------------- // 2. PRINT THE STRINGS @@ -45,6 +49,11 @@ int main(int argc, const char** argv) { std::cout << "C-string (const char*): " << hello_c_c << std::endl; std::cout << "C++ string: " << hello_cpp << std::endl; std::cout << "C++ string_view: " << hello_sv << std::endl; + // As std::cout _does not_ understand llvm::StringRef, you need to grab the + // underlying string for printing. + std::cout << "C++ StringRef (via std::cout): " << hello_sr.str() << std::endl; + // However, llvm::outs() _does_ understand llvm:StringRef. + llvm::outs() << "C++ StringRef (via llvm::outs): " << hello_sr << "\n"; std::cout << std::endl; //------------------------------------------------------------------------- @@ -54,6 +63,7 @@ int main(int argc, const char** argv) { std::cout << "Size of hello_c_c: " << sizeof(hello_c_c) << std::endl; std::cout << "Size of hello_cpp: " << sizeof(hello_cpp) << std::endl; std::cout << "Size of hello_sv: " << sizeof(hello_sv) << std::endl; + std::cout << "Size of hello_sr: " << sizeof(hello_sr) << std::endl; std::cout << std::endl; //-------------------------------------------------------------------------