Skip to content

cargs

CI/CD Pipeline CodeQL Analysis License: MIT

Modern C library for command-line argument parsing with an elegant, macro-based API.

cargs is a powerful C library for handling command-line arguments, designed to be both simple to use and flexible enough for advanced usage scenarios.

✨ Features

  • πŸ“‹ Help generation: automatic formatted help and usage display
  • πŸ”„ Typed options: booleans, integers, strings, floats, arrays, maps
  • 🎨 Flexible format parsing: supports multiple option formats (--option=value, --option value, -ovalue, etc.)
  • 🌳 Subcommands: Git/Docker-style nested command support
  • ⚠️ Clear error reporting: detailed and user-friendly error messages for invalid options or values
  • ✨ Elegant design: define options with concise, expressive macros
  • πŸ” Built-in validators: built-in range, choices, regex patterns with comprehensive predefined sets
  • πŸ“¦ Organized option grouping: visually group related options in help displays
  • πŸ”— Option relationships: define dependencies and conflicts between options
  • 🚦 Smart validation: comprehensive option structure checking during development to prevent runtime errors, with a release mode for optimal performance in production
  • 🌐 Environment variables: automatic ENV configuration
  • πŸš€ Memory efficiency: minimizes heap allocations for better performance and reliability
  • 🧰 Easy option customization: create your own option types and handlers
  • πŸ›‘οΈ Custom validation pipeline: design your own validators with flexible pre/post processing

Quick Example

#include "cargs.h"
#include <stdio.h>

// Define options
CARGS_OPTIONS(
    options,
    HELP_OPTION(FLAGS(FLAG_EXIT)),
    VERSION_OPTION(FLAGS(FLAG_EXIT)),
    OPTION_FLAG('v', "verbose", HELP("Enable verbose output")),
    OPTION_STRING('o', "output", HELP("Output file"), DEFAULT("output.txt")),
    OPTION_INT('p', "port", HELP("Port number"), RANGE(1, 65535), DEFAULT(8080)),
    POSITIONAL_STRING("input", HELP("Input file"))
)

int main(int argc, char **argv)
{
    // Initialize cargs
    cargs_t cargs = cargs_init(options, "my_program", "1.0.0");
    cargs.description = "cargs demonstrator";

    // Parse arguments
    if (cargs_parse(&cargs, argc, argv) != CARGS_SUCCESS) {
        return 1;
    }

    // Access parsed values
    const char *input = cargs_get(cargs, "input").as_string;
    const char *output = cargs_get(cargs, "output").as_string;
    int port = cargs_get(cargs, "port").as_int;
    bool verbose = cargs_get(cargs, "verbose").as_bool;

    printf("Configuration:\n");
    printf("  Input: %s\n", input);
    printf("  Output: %s\n", output);
    printf("  Port: %d\n", port);
    printf("  Verbose: %s\n", verbose ? "yes" : "no");

    // Free resources
    cargs_free(&cargs);
    return 0;
}

πŸš€ Getting Started

πŸ“š Documentation

The documentation is organized as follows: