Environment Variables
Environment variables are key-value pairs that live outside your program, in the shell or process environment that launches it. They are a common way to pass configuration into a program without hardcoding values in source code — things like API keys, file paths, feature flags, or the current locale. C provides a small standard library interface for reading them, plus some widely available (but non-standard) functions for setting them.
Reading a Variable with getenv
The standard function for reading an environment variable is getenv, declared in stdlib.h. You give it a variable name and it returns a pointer to the value string, or NULL if the variable is not set.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *home = getenv("HOME");
if (home != NULL) {
printf("HOME is set to: %s\n", home);
} else {
printf("HOME is not set.\n");
}
return 0;
}Setting Environment Variables
Standard C (the C language as defined by ISO/IEC 9899) does not define a portable function for setting environment variables. On POSIX systems (Linux, macOS, BSD), you have setenv and putenv, declared in stdlib.h.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
/* setenv(name, value, overwrite) */
if (setenv("MY_APP_MODE", "debug", 1) != 0) {
perror("setenv failed");
return EXIT_FAILURE;
}
printf("MY_APP_MODE = %s\n", getenv("MY_APP_MODE"));
return EXIT_SUCCESS;
}Function | Header | Portability | Notes |
|---|---|---|---|
getenv | stdlib.h | Standard C | Read-only, returns NULL if unset |
setenv | stdlib.h | POSIX only | Not available on plain Windows/MSVC |
putenv | stdlib.h | POSIX (also on Windows as _putenv) | Takes a "NAME=value" string |
Practical Use Case: Configuration Without Hardcoding
A very common real-world pattern is reading configuration such as an API key or a database URL from the environment instead of hardcoding it in source code (which would risk committing secrets to version control). Here is a small example that falls back to a default when a variable is missing:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
const char *api_key = getenv("MY_APP_API_KEY");
if (api_key == NULL) {
fprintf(stderr, "Warning: MY_APP_API_KEY not set, using default.\n");
api_key = "demo-key-only";
}
printf("Using API key: %s\n", api_key);
/* ... use api_key to configure an HTTP client, etc. ... */
return EXIT_SUCCESS;
}$ MY_APP_API_KEY=sk-real-secret ./app
Using API key: sk-real-secret
Summary
getenv("NAME") reads a variable, returning NULL if it is not set — always check.
setenv/putenv can set variables but are POSIX extensions, not standard C.
Reading configuration from the environment is a common way to avoid hardcoding secrets.
Environment variables are visible to the whole process, not a secure secrets store.