Example 1 — A header with a struct and inline helpers
Save as rect.h, then include it from main.c.
/* rect.h */
#ifndef RECT_H
#define RECT_H
struct Rect { int w, h; };
static inline int rect_area(struct Rect r) { return r.w * r.h; }
static inline int rect_perimeter(struct Rect r) { return 2 * (r.w + r.h); }
#endif
/* main.c */
#include <stdio.h>
#include "rect.h"
int main(void) {
struct Rect r = {4, 3};
printf("area = %d, perimeter = %d\n", rect_area(r), rect_perimeter(r));
return 0;
} How It Works
- The header defines a type and two tiny
static inlinehelpers. - Each file that includes it gets its own copy, so there is no linker conflict.
- 4 * 3 = 12 and 2 * (4 + 3) = 14.
