Environment Variables in C++

Our first example demonstrates how to work with environment variables in C++. Environment variables are a universal mechanism for conveying configuration information to programs.

#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>

int main() {
    // To set a key/value pair, use setenv
    // To get a value for a key, use getenv
    // getenv will return nullptr if the key isn't present in the environment
    setenv("FOO", "1", 1);
    std::cout << "FOO: " << (getenv("FOO") ? getenv("FOO") : "") << std::endl;
    std::cout << "BAR: " << (getenv("BAR") ? getenv("BAR") : "") << std::endl;

    // To list all key/value pairs in the environment, we can use the environ variable
    std::cout << std::endl;
    for (char** env = environ; *env != nullptr; ++env) {
        std::string pair = *env;
        size_t pos = pair.find('=');
        if (pos != std::string::npos) {
            std::cout << pair.substr(0, pos) << std::endl;
        }
    }

    return 0;
}

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is empty.

$ g++ environment_variables.cpp -o environment_variables
$ ./environment_variables
FOO: 1
BAR: 

The list of keys in the environment will depend on your particular machine.

TERM_PROGRAM
PATH
SHELL
...
FOO

If we set BAR in the environment first, the running program picks that value up.

$ export BAR=2
$ ./environment_variables
FOO: 1
BAR: 2
...

In C++, we use setenv to set environment variables and getenv to retrieve them. The environ variable gives us access to all environment variables. Remember to include the necessary headers (<cstdlib> for environment functions and <iostream> for input/output operations) when working with environment variables in C++.

Markdown formatting for Hugo

This C++ code example is formatted in Markdown, which is suitable for Hugo. The code blocks are enclosed in triple backticks (```) with the language specified (cpp). The output and shell commands are also in code blocks, but without a language specification.

The explanations are in plain text, with important terms or command names enclosed in single backticks (`). This formatting style is consistent with Hugo’s requirements and provides good readability for both the code and the explanations.