Skip to content

dmazzella/dotenv

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 

Repository files navigation

dotenv.h

A lightweight, header-only C++ library for loading environment variables from .env files. Zero dependencies, cross-platform compatible.

Features

Single header-only - Just include dotenv.h and you're ready
Multi-line values - Support for quoted multi-line strings
Variable expansion - Use $VAR or ${VAR} syntax
Escaped characters - Handle \", \', and \\ properly
Comments - Inline comments with #
Cross-platform - Works on Windows (MSVC, MinGW), Linux, and macOS
No dependencies - Only standard C++ library

Installation

Simply copy dotenv.h to your project and include it:

#include "dotenv.h"

Quick Start

1. Create a .env file

# Database configuration
DATABASE_HOST=localhost
DATABASE_PORT=5432
DATABASE_NAME=myapp
DATABASE_PASSWORD='my$ecure!p@ss'

# Multi-line JSON configuration
API_CONFIG='{
  "endpoint": "https://api.example.com",
  "timeout": 30,
  "retries": 3
}'

# Variable expansion
BASE_PATH=/home/user
DATA_PATH=$BASE_PATH/data
LOG_PATH=${BASE_PATH}/logs

2. Load variables in your code

#include <iostream>
#include <cstdlib>
#include "dotenv.h"

int main() {
    // Load .env file from current directory
    dotenv::init();

    // Or specify a custom path
    // dotenv::init("config/.env");

    // Access variables using standard getenv
    std::cout << "Host: " << std::getenv("DATABASE_HOST") << std::endl;
    std::cout << "Port: " << std::getenv("DATABASE_PORT") << std::endl;

    // Use dotenv::getenv for default values
    std::string host = dotenv::getenv("DATABASE_HOST", "localhost");

    return 0;
}

3. Compile and run

# GCC/Clang
g++ -std=c++11 main.cpp -o myapp

# MSVC
cl /EHsc /std:c++14 main.cpp

# Run
./myapp

Supported Syntax

Basic key-value pairs

KEY=value
NUMERIC=12345
EMPTY=

Quoted values (single or double quotes)

SINGLE_QUOTED='value with spaces'
DOUBLE_QUOTED="value with spaces"

Escaped characters

ESCAPED_QUOTES='value with \'single\' quotes'
ESCAPED_DOUBLE="value with \"double\" quotes"
ESCAPED_BACKSLASH='path\\to\\file'

Multi-line values (must be quoted)

SQL_QUERY="
  SELECT * FROM users
  WHERE status = 'active'
  ORDER BY created_at DESC
"

JSON_CONFIG='{
  "key": "value",
  "nested": {
    "array": [1, 2, 3]
  }
}'

Comments

# Full line comment
KEY=value  # Inline comment (ignored)

Variable expansion

BASE=/home/user
PATH1=$BASE/documents      # Using $VAR
PATH2=${BASE}/downloads    # Using ${VAR}

API Reference

dotenv::init(filename)

Loads environment variables from the specified file.

dotenv::init();                    // Loads .env from current directory
dotenv::init("config/app.env");   // Loads from custom path

dotenv::init(flags, filename)

Loads with flags to control behavior.

dotenv::init(dotenv::Preserve, ".env");  // Don't overwrite existing env vars
dotenv::init(dotenv::OptionsNone, ".env");  // Always overwrite (default)

dotenv::getenv(name, default)

Gets an environment variable with an optional default value.

std::string host = dotenv::getenv("DATABASE_HOST", "localhost");
std::string port = dotenv::getenv("DATABASE_PORT", "5432");

Known Limitations

  • ❌ Unquoted multi-line values are not supported
  • ❌ Mixed quote types (e.g., 'value") won't work
  • ❌ Comments inside multi-line quoted values become part of the value
  • export keyword is not supported (treated as part of variable name)

Examples

See test_dotenv.cpp and test_dotenv.env for comprehensive examples.

Example: Database Configuration

#include <iostream>
#include "dotenv.h"

int main() {
    dotenv::init("database.env");

    std::string connString =
        "host=" + dotenv::getenv("DB_HOST", "localhost") +
        " port=" + dotenv::getenv("DB_PORT", "5432") +
        " dbname=" + std::string(std::getenv("DB_NAME")) +
        " user=" + std::string(std::getenv("DB_USER"));

    std::cout << "Connection: " << connString << std::endl;
    return 0;
}

Example: JSON Configuration

#include <iostream>
#include "dotenv.h"

int main() {
    dotenv::init();

    // Load multi-line JSON config
    const char* config = std::getenv("API_CONFIG");
    if (config) {
        // Parse with your favorite JSON library
        std::cout << "Config: " << config << std::endl;
    }

    return 0;
}

Running Tests

# Compile the test suite
g++ -std=c++11 test_dotenv.cpp -o test_dotenv
# Or with MSVC
cl /EHsc /std:c++14 test_dotenv.cpp

# Run tests
./test_dotenv

Requirements

  • C++11 or later
  • Standard C++ library

License

See LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit issues or pull requests.

Version

Current version: 1.0.0

About

A lightweight, header-only C++ library for loading environment variables from .env files

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages