dotenv is a minimalistic, header-only C++ library that brings .env-style environment variable management to your C++ projects, inspired by the simplicity of dotenv in other languages. It’s designed to load, set, and retrieve environment variables, letting you keep configurations out of your code and in a clean, readable .env file. Best of all? No dependencies. It just works.
- Loads environment variables from a
.env
file inKEY=VALUE
format. - Provides functions to retrieve variables with an optional default value.
- Allows setting environment variables programmatically in the current process.
- Works across platforms (Windows, Linux, macOS).
Since dotenv
is a header-only library, there's no need to compile or link any external files. Simply download or clone this repository and include dotenv.h
in your project.
To use dotenv
, include the dotenv.h
header file in your C++ project. Here’s a quick example.
Create a .env
file with some environment variables. For example:
# .env
DB_HOST=127.0.0.1
DB_USER=admin
DB_PASSWORD=secret
In your C++ code, include dotenv.h
and use dotenv
to load and retrieve environment variables.
#include "dotenv.h"
#include <iostream>
int main() {
dotenv env(".env"); // Load variables from .env file
// Retrieve variables with default values if they are not set
std::string db_host = env.get("DB_HOST", "localhost");
std::string db_user = env.get("DB_USER", "root");
std::string db_password = env.get("DB_PASSWORD", "");
std::cout << "Database Host: " << db_host << std::endl;
std::cout << "Database User: " << db_user << std::endl;
std::cout << "Database Password: " << db_password << std::endl;
// Set a new environment variable within this process
env.set("NEW_VAR", "new_value");
std::cout << "New Variable: " << env.get("NEW_VAR") << std::endl;
return 0;
}
Since dotenv
is a header-only library, you don’t need to link any additional files. Compile your program as usual:
g++ main.cpp -o main
- Load from
.env
:dotenv env(".env");
loads environment variables from the specified.env
file. - Retrieve with Defaults:
env.get("DB_HOST", "localhost");
retrieves theDB_HOST
variable, or returns"localhost"
ifDB_HOST
is not set. - Set New Variables:
env.set("NEW_VAR", "new_value");
sets a new variable within the current process.
dotenv
uses _putenv_s
on Windows and setenv
on Unix-like systems to set environment variables. This ensures cross-platform compatibility, allowing you to use the same code on Windows, macOS, and Linux.
For information on setting up and running tests for dotenv
, please refer to the Testing Instructions.
This project is licensed under the MIT License - see the LICENSE
file for details.
Contributions are welcome! Feel free to fork this repository and submit a pull request for any bug fixes or new features.