// sample-header-only.hpp: a header-only C++ library, guarded with #pragma once. // Free sample from 99helpers.com/file-types/h // // "Header-only" means there is no .cpp file to compile or link: including // this header is all it takes. sample-main.cpp uses it. // #pragma once does the job of an include guard in one line. It isn't in the // C or C++ standard, but GCC, Clang and MSVC all support it. #pragma once #include #include #include #include namespace sample { // Templates live in headers: the compiler needs the full definition to // generate code for each type it's used with. template double average(const std::vector& values) { if (values.empty()) { return 0.0; } return static_cast(std::accumulate(values.begin(), values.end(), T{})) / static_cast(values.size()); } // An ordinary function defined in a header must be marked inline. Without // it, every .cpp file that includes the header defines its own copy and the // linker reports "multiple definition". inline std::string bar(double value, double max, std::size_t width = 20) { if (max <= 0.0 || value <= 0.0) { return {}; } auto filled = static_cast(value / max * static_cast(width) + 0.5); return std::string(filled > width ? width : filled, '#'); } // inline variables (C++17) follow the same rule for constants and globals. inline constexpr const char* library_name = "99helpers sample bars"; } // namespace sample