std::getenv(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

Hey bestie πŸ’– welcome to std::getenv(3) from the C++ Standard Libary manual β€” yes, that’s the manual name up top, and we’re folding it in right here instead of copying the header line. Let’s get into it 🫢

🌸 NAME 🌸

std::getenv β€” std::getenv. That’s literally the name, bestie ✨

✨ Synopsis ✨

Defined in header <cstdlib>

char* getenv( const char* env_var );

Okay so what it does πŸ‘€: it searches the environment list provided by the host environment (the OS) for a string that matches the C string pointed to by env_var, and returns a pointer to the C string that is associated with the matched environment list member. Slay.

Thread-safety tea β˜•: this function is not required to be thread-safe. (until C++11) Another call to getenv, as well as a call to the POSIX functions setenv(), unsetenv(), and putenv(), may invalidate the pointer returned by a previous call or modify the string obtained from a previous call.

This function is thread-safe (calling it from multiple threads does not introduce a data race) as long as no other function modifies the host environment. (since C++11) In particular, the POSIX functions setenv(), unsetenv(), and putenv() would introduce a data race if called without synchronization.

And please, bestie β€” modifying the string returned by getenv invokes undefined behavior. πŸ’€ Not cute, not iconic, do not do it.

πŸŽ€ Parameters πŸŽ€

  • env_var β€” a null-terminated character string identifying the name of the environmental variable to look for πŸ”

πŸ’œ Return value πŸ’œ

A character string identifying the value of the environmental variable β€” or a null pointer if such variable is not found. Simple as that πŸ¦‹

πŸ¦‹ Notes πŸ¦‹

On POSIX systems, the environment variables are also accessible through the global variable environ, declared as extern char** environ; in <unistd.h>, and through the optional third argument, envp, of the main function. iykyk 🌈

πŸ”₯ Example πŸ”₯

// Run this code

#include <cstdlib>
#include <iostream>

int main()
{
    if (const char* env_p = std::getenv("PATH"))
        std::cout << "Your PATH is: " << env_p << '\n';
}

Possible output:

Your PATH is: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

πŸ‘‘ See also πŸ‘‘

C documentation for getenv 🧚


Signed, sealed, delivered, bestie πŸ’…: this page comes from http://cppreference.com, dated 2024.06.10, and it’s page std::getenv(3). Mwah πŸ’‹

πŸ“¦ where this page comes from