Command Line Arguments and Environment Variables

In this lecture, we’ll explore how to pass arguments to a C++ program via the command line and how programs can utilize environment variables provided by the operating system. These mechanisms allow a program to receive input or configuration information when it starts, making our programs more flexible and powerful. Understanding these concepts will enable you to write programs that can handle user input from the command line and adapt to different system settings.

Command-Line Arguments

Command-line arguments allow a user to provide information to a program at the time of executing it from a terminal or command prompt. Instead of prompting the user for input after the program starts, you can supply inputs (like filenames, numbers, or options) as part of the command that runs the program. This is useful for automation and scripting, since the program can start up already knowing what to do.

For example, command-line arguments are commonly used to:

In C++, to receive command-line arguments, you define the main function with parameters. The typical signature is:

int main(int argc, char* argv[])

By convention, the parameters are named argc and argv. Next, we'll explain what these mean and how to use them.

Main Function Parameters: argc and argv

argc (argument count) is an integer that holds the number of command-line arguments passed to the program. This count includes the program’s name itself as the first argument, so argc is always at least 1. Each additional item typed after the program name in the command line increases the argc count by one.

argv (argument vector) is an array of C-style strings (char*) that contains the actual arguments. argv[0] is the program’s name as invoked, argv[1] is the first argument after the program name, argv[2] is the second argument, and so on. The length of this array is argc.

Let's look at a simple program that prints out all the command-line arguments it receives:

#include <iostream>
using namespace std;

int main(int argc, char* argv[]) {
    cout << "Number of arguments: " << argc << endl;
    for (int i = 0; i < argc; ++i) {
        cout << "Arg " << i << ": " << argv[i] << endl;
    }
    return 0;
}

This program prints the total number of arguments, then iterates through the argv array and prints each argument on its own line (prefixed with its index). If we compile this into an executable (say, MyArgs) and run it with some arguments, we might see output like:

$ ./MyArgs file.txt 100  
Number of arguments: 3  
Arg 0: ./MyArgs  
Arg 1: file.txt  
Arg 2: 100  

In this example, we ran the program as ./MyArgs file.txt 100. The output shows that argc was 3: the program name (./MyArgs) plus two additional arguments. We see argv[0] contains "./MyArgs", argv[1] contains "file.txt", and argv[2] contains "100" – exactly what was passed in.

Note that command-line arguments are always received as strings. For instance, the argument "100" is a string, not the integer 100. If your program needs to treat it as a number, you must convert it (e.g., using std::stoi, atoi, or a stringstream). Also, if no arguments (other than the program name) are provided, argc will be 1. Programs often check argc and display a usage message or default behavior when expected arguments are missing.

Quiz: Understanding Command-Line Arguments

Suppose you run a C++ program with the command: ./app foo bar. Which of the following is true about the arguments received in main?

Coding Exercise: Printing Command-Line Arguments

Write a C++ program that does the following:


Answer:

Environment Variables

Environment variables are dynamic values defined in the operating system or shell that are passed into programs. They serve as a way to configure or provide information to processes globally, without using explicit command-line arguments. Each environment variable has a name and a value. For example, the environment variable PATH holds a list of directories where the system looks for executable programs.

You can set or view environment variables in your shell. For instance, on a Unix-like system:

$ export MYNAME="Alice"
$ echo $MYNAME
Alice

This example creates an environment variable MYNAME and then prints it. You can list all environment variables by running env or printenv in a Unix shell.

Common environment variables include:

Programs can read these variables to adjust their behavior based on the environment. In C++, environment variables can be accessed using the standard library function getenv (declared in <cstdlib>). The getenv function takes the name of an environment variable and returns a pointer to a C-string with its value (or NULL if that variable is not set).

// Example: using getenv to retrieve an environment variable
#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
    const char* pathValue = getenv("PATH");
    if (pathValue) {
        cout << "PATH environment variable: " << pathValue << endl;
    } else {
        cout << "PATH is not set." << endl;
    }
    return 0;
}

In the above code, if the PATH variable exists in the environment, it prints its value; otherwise it prints a message that PATH is not set. Typically, PATH will be set, and you would see a long string of directories separated by colons. Programs can similarly query other environment variables by name using getenv.

Quiz: Environment Variables

Which of the following statements about environment variables is false?

Coding Exercise: Using Environment Variables

Create a C++ program that produces a personalized greeting using environment variables and command-line arguments. Your program should:

Output the greeting message along with the home directory information (if available).


Answer: