Skip to content

Hreflang Tag Generator — C source

Turn a list of language versions into a valid hreflang set — locale normalization, duplicate detection and x-default handling — emitted as HTML link tags or an XML sitemap block.

This is the C implementation — the same logic the interactive tool runs, in a shareable, citable form.

// =============================================================================
//  hreflang-tag-generator — locale-list validation + alternate-link emission
//  (polyglot showcase: C)
//  CosmoDev polyglot port of the SEO/meta trio's hreflang logic.
//  Display source — part of CosmoDev's polyglot tool pages.
//
//  Port of src/lib/hreflang.ts — same logic as this dir's typescript.ts and
//  the live Go twin at cli/hreflang-tag-generator/hreflang-tag-generator.go.
//  C has no regex in its standard library, so the anchored TS patterns
//  (^[a-zA-Z]{2}$, ^[a-zA-Z]{2}-[a-zA-Z]{2}$, ^https?://) are hand-rolled
//  character tests; all strings live in caller-sized buffers.
// =============================================================================

#include <stddef.h>
#include <stdio.h>
#include <string.h>

#define HL_MAX_ROWS 64
#define HL_MAX_LINE 256
#define HL_MAX_ERRORS 16

/** One locale/URL pair. Mirrors the TS HreflangRow interface. */
typedef struct {
  const char *locale;
  const char *url;
} HreflangRow;

/** The field set for hl_build_hreflang — rows plus an optional x-default. */
typedef struct {
  HreflangRow rows[HL_MAX_ROWS];
  size_t row_count;
  const char *x_default_url; /* NULL = absent */
} HreflangInput;

/** Diagnostics plus both emitted flavors. On failure ok is 0, each errors[]
 * entry (error_count of them) is one row-located problem, and html/sitemap
 * are empty — exactly like the TS result. */
typedef struct {
  int ok;
  char errors[HL_MAX_ERRORS][HL_MAX_LINE];
  size_t error_count;
  char html[HL_MAX_ROWS * HL_MAX_LINE];
  char sitemap[HL_MAX_ROWS * HL_MAX_LINE];
} HreflangResult;

/** TS String#trim() — strips ASCII whitespace from both ends. */
static void hl_trim(const char *s, char *out) {
  size_t len;
  while (*s == ' ' || (*s >= '\t' && *s <= '\r')) s++;
  len = strlen(s);
  while (len > 0) {
    char c = s[len - 1];
    if (!(c == ' ' || (c >= '\t' && c <= '\r'))) break;
    len--;
  }
  memcpy(out, s, len);
  out[len] = '\0';
}

static int hl_is_alpha(char c) {
  return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}

static char hl_lower(char c) {
  return (c >= 'A' && c <= 'Z') ? (char)(c + 32) : c;
}

static char hl_upper(char c) {
  return (c >= 'a' && c <= 'z') ? (char)(c - 32) : c;
}

/** Append src to dst (both HL_MAX_ROW*HL_MAX_LINE bounded). */
static void hl_append(char *dst, const char *src) {
  strcat(dst, src);
}

/** Normalize a locale tag to Google's hreflang grammar: ll (ISO-639-1,
 * lowercase) or ll-CC (region uppercase, ISO-3166). Case and surrounding
 * whitespace are corrected ("en-us" -> "en-US"); anything else is invalid
 * and returns 0. The C twin of normalizeLocale() in src/lib/hreflang.ts —
 * the 0 return stands in for the TS null. */
static int hl_normalize_locale(const char *raw, char *out) {
  char t[HL_MAX_LINE];
  size_t n;
  hl_trim(raw, t);
  n = strlen(t);
  if (n == 2 && hl_is_alpha(t[0]) && hl_is_alpha(t[1])) {
    out[0] = hl_lower(t[0]);
    out[1] = hl_lower(t[1]);
    out[2] = '\0';
    return 1;
  }
  if (n == 5 && t[2] == '-' && hl_is_alpha(t[0]) && hl_is_alpha(t[1]) &&
      hl_is_alpha(t[3]) && hl_is_alpha(t[4])) {
    out[0] = hl_lower(t[0]);
    out[1] = hl_lower(t[1]);
    out[2] = '-';
    out[3] = hl_upper(t[3]);
    out[4] = hl_upper(t[4]);
    out[5] = '\0';
    return 1;
  }
  out[0] = '\0';
  return 0;
}

/** Trim raw and return 1 with the trimmed value in out when it starts with
 * http:// or https://, otherwise 0. Mirrors the TS validUrl() helper. */
static int hl_valid_url(const char *raw, char *out) {
  hl_trim(raw, out);
  return strncmp(out, "http://", 7) == 0 || strncmp(out, "https://", 8) == 0;
}

static void hl_push_error(HreflangResult *r, const char *msg) {
  if (r->error_count < HL_MAX_ERRORS) {
    strncpy(r->errors[r->error_count], msg, HL_MAX_LINE - 1);
    r->errors[r->error_count][HL_MAX_LINE - 1] = '\0';
  }
  r->error_count++;
}

/** Validate a locale/URL table and emit both hreflang flavors. Invalid input
 * collects every error (row-located) and emits empty blocks; valid input
 * normalizes locales, preserves row order, and appends x-default last. */
static void hl_build_hreflang(const HreflangInput *input, HreflangResult *result) {
  char normalized[HL_MAX_ROWS][16];
  char urls[HL_MAX_ROWS][HL_MAX_LINE];
  size_t normalized_count = 0;
  char seen[HL_MAX_ROWS][16];
  size_t seen_count = 0;
  char x_default[HL_MAX_LINE];
  int has_x_default = 0;
  size_t i;
  char t[HL_MAX_LINE];

  memset(result, 0, sizeof(*result));

  for (i = 0; i < input->row_count; i++) {
    size_t n = i + 1;
    const HreflangRow *row = &input->rows[i];
    char locale[16];
    char url[HL_MAX_LINE];
    char msg[HL_MAX_LINE];
    int duplicate = 0;
    size_t j;
    const char *raw_locale = row->locale ? row->locale : "";

    if (!hl_normalize_locale(raw_locale, locale)) {
      char trimmed[HL_MAX_LINE];
      hl_trim(raw_locale, trimmed);
      snprintf(msg, sizeof(msg),
               "Row %d: \"%s\" is not a valid locale \xe2\x80\x94 use ll or ll-CC "
               "(e.g. en, de-AT).",
               (int)n, trimmed);
      hl_push_error(result, msg);
      continue;
    }
    for (j = 0; j < seen_count; j++) {
      if (strcmp(seen[j], locale) == 0) duplicate = 1;
    }
    if (duplicate) {
      snprintf(msg, sizeof(msg), "Row %d: locale \"%s\" is already used.", (int)n, locale);
      hl_push_error(result, msg);
      continue;
    }
    {
      char url_trim[HL_MAX_LINE];
      hl_trim(row->url ? row->url : "", url_trim);
      if (url_trim[0] == '\0') {
        snprintf(msg, sizeof(msg), "Row %d: URL is required.", (int)n);
        hl_push_error(result, msg);
        continue;
      }
    }
    if (!hl_valid_url(row->url ? row->url : "", url)) {
      snprintf(msg, sizeof(msg),
               "Row %d: URL must start with http:// or https://.", (int)n);
      hl_push_error(result, msg);
      continue;
    }
    memcpy(seen[seen_count], locale, 16);
    seen_count++;
    memcpy(normalized[normalized_count], locale, 16);
    hl_trim(url, urls[normalized_count]);
    normalized_count++;
  }

  x_default[0] = '\0';
  if (input->x_default_url != NULL) {
    hl_trim(input->x_default_url, t);
    if (t[0] != '\0') {
      if (!hl_valid_url(input->x_default_url, x_default)) {
        hl_push_error(result,
                      "x-default: URL must start with http:// or https://.");
        x_default[0] = '\0';
      } else {
        has_x_default = 1;
      }
    }
  }

  if (result->error_count > 0) {
    return;
  }
  result->ok = 1;

  for (i = 0; i < normalized_count; i++) {
    char line[HL_MAX_LINE];
    snprintf(line, sizeof(line),
             "<link rel=\"alternate\" href=\"%s\" hreflang=\"%s\" />\n",
             urls[i], normalized[i]);
    hl_append(result->html, line);
    snprintf(line, sizeof(line),
             "    <xhtml:link rel=\"alternate\" hreflang=\"%s\" href=\"%s\"/>\n",
             normalized[i], urls[i]);
    hl_append(result->sitemap, line);
  }
  if (has_x_default) {
    char line[HL_MAX_LINE];
    snprintf(line, sizeof(line),
             "<link rel=\"alternate\" href=\"%s\" hreflang=\"x-default\" />\n",
             x_default);
    hl_append(result->html, line);
    snprintf(line, sizeof(line),
             "    <xhtml:link rel=\"alternate\" hreflang=\"x-default\" href=\"%s\"/>\n",
             x_default);
    hl_append(result->sitemap, line);
  }
  /* The TS lib joins lines with \n (no trailing newline); drop the last. */
  {
    size_t hl = strlen(result->html);
    size_t sl = strlen(result->sitemap);
    if (hl > 0) result->html[hl - 1] = '\0';
    if (sl > 0) result->sitemap[sl - 1] = '\0';
  }
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →