/* * sample-header.h: a C header for a tiny statistics library, with numbered * comments. Free sample from 99helpers.com/file-types/h * * The functions declared here are defined in sample-header.c. Two programs * use them: sample-main.c (C) and sample-main.cpp (C++). * cc -Wall -Wextra -std=c17 sample-main.c sample-header.c -o stats-c * cc -Wall -Wextra -std=c17 -c sample-header.c * c++ -Wall -Wextra -std=c++20 sample-main.cpp sample-header.o -o stats-cpp */ /* 1. The include guard. If this file is included twice in one source file * (often indirectly, through another header), the second copy sees * SAMPLE_HEADER_H already defined and skips everything up to #endif. */ #ifndef SAMPLE_HEADER_H #define SAMPLE_HEADER_H /* 2. Headers this header needs for its own declarations (size_t, bool). * A header should compile on its own, whatever was included before it. */ #include #include /* 3. C linkage for C++. C++ compilers "mangle" function names to encode their * parameter types; extern "C" tells a C++ compiler these functions use * plain C names, so C++ code can link to the compiled C library. */ #ifdef __cplusplus extern "C" { #endif /* 4. Macros and constants: a version string and a size limit. */ #define STATS_VERSION "1.0.0" #define STATS_MAX_VALUES 64 /* 5. A type definition. Because the whole struct is visible here, callers * can create one as an ordinary local variable. */ typedef struct { double values[STATS_MAX_VALUES]; size_t count; } stats_t; /* 6. Function declarations (prototypes): the name, parameters and return * type, ending in a semicolon instead of a body. The bodies are in * sample-header.c, compiled once and linked into every program. */ void stats_init(stats_t *s); bool stats_add(stats_t *s, double value); double stats_mean(const stats_t *s); double stats_min(const stats_t *s); double stats_max(const stats_t *s); /* 7. A variable declaration. extern says "this exists somewhere else": * sample-header.c holds the one definition. Without extern, every file * including this header would define its own copy, and linking fails. */ extern const char stats_library_name[]; /* 8. A static inline function: one of the few things whose full definition * belongs in a header. Each file that includes it gets its own copy, * which the compiler usually inlines. */ static inline size_t stats_count(const stats_t *s) { return s->count; } /* 9. The end of the extern "C" block. */ #ifdef __cplusplus } #endif /* 10. The end of the include guard. */ #endif /* SAMPLE_HEADER_H */