Skip to content

Commit

Permalink
Add examples with LLVM's StringRef
Browse files Browse the repository at this point in the history
Also adds LLVM's libLLVMSUpport as a dependency.
  • Loading branch information
banach-space committed Dec 7, 2024
1 parent b520d8a commit 0690d6d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
6 changes: 5 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,10 @@ target_compile_options(${executable} PRIVATE
"$<$<CXX_COMPILER_ID:MSVC>:${cpp-tutor_COMPILER_OPTIONS_MSVC}>")
endforeach()

target_link_libraries(strings_1
LLVMSupport
)


# EXTRA SET-UP FOR UNIT TESTS
# ===========================
Expand All @@ -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
)
)
10 changes: 10 additions & 0 deletions src/strings_1_main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
#include <cppt_ag.hpp>
#include <cppt_tools.hpp>

#include "llvm/Support/raw_ostream.h"
#include <llvm/ADT/StringRef.h>

#include <algorithm>
#include <iostream>
#include <string>
Expand All @@ -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
Expand All @@ -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;

//-------------------------------------------------------------------------
Expand All @@ -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;

//-------------------------------------------------------------------------
Expand Down

0 comments on commit 0690d6d

Please sign in to comment.