A lightweight C++ library for loading and parsing environment variables from a .env file with JavaScript-like variable expansion.
- This project is owned by @harshfeudal.
- A header-only C++ library perfect for managing configuration variables, such as tokens for a Discord bot using D++. Use with
.gitignoreto keep your.envfile secure.
- Download the
dotenvfolder containingdotenv.h. - Include and use it in your project like this:
main.cpp
#include <dotenv/dotenv.h>
#include <iostream>
int main() {
Dotenv env;
// Load your .env file
if (!env.load(".env")) {
std::cerr << "Failed to load .env file" << std::endl;
return 1;
}
// Read your .env variable
std::string my_var = env.get("MY_VAR");
std::cout << "The variable is: " << my_var << std::endl;
// Get with default value
std::string missing_var = env.get("MISSING", "default value");
std::cout << "Missing variable: " << missing_var << std::endl;
return 0;
}Note: If you would like to use the non-OOP version, please include only dotenv-alt.h. It provides a set of functions instead of a class-based interface. This can be useful for simpler use cases or when you prefer a procedural approach.
- Formatted Strings: Supports escape sequences in double-quoted values:
SENTENCE="\n\"Hello World\"\n\t- Hello 2025 -"Outputs:
The sentence is:
"Hello World"
- Hello 2025 -- Comments: Ignores content after
#when not in quotes:
TOKEN="WW91ckRpc2NvcmRCb3RUb2tlbg==" # Your Discord bot token-
Header-Only: Just include
dotenv.h- no additional linking required! -
Variable Expansion: JavaScript-like variable substitution:
$KEYor${KEY}expands to the value of KEY\$KEYescapes the expansion${KEY:-default}uses "default" if KEY is unset
Example:
HOST=localhost
URL=$HOST:8080
SAFE=\$HOST
FALLBACK=${UNSET:-default}-
Quote Support: Supports single (
'), double ("), and backtick (`) quotes. Only double-quoted values process escapes. -
Empty Values: Handles empty variables:
- Microsoft Windows 10/11
x64/x86 - Visual Studio platform
x64/x86 - C++17 ISO/IEC
14882
Contributions are welcome! Please:
- Test your changes thoroughly
- Submit a pull request
Don't worry about mistakes - we'll work together to refine it
Get the latest version here.
Please leave a star if you like it. Thank you!
