Command Line Arguments in Cilk

Command-line arguments are a common way to parameterize execution of programs. For example, ./program arg1 arg2 uses arg1 and arg2 as arguments to the program.

#include <cilk/cilk.h>
#include <iostream>
#include <vector>
#include <string>

int main(int argc, char* argv[]) {
    // argv provides access to raw command-line arguments.
    // Note that the first value in this array is the path to the program,
    // and argv[1] onwards holds the arguments to the program.
    std::vector<std::string> argsWithProg(argv, argv + argc);
    std::vector<std::string> argsWithoutProg(argv + 1, argv + argc);

    // You can get individual args with normal indexing.
    std::string arg = argv[3];

    for (const auto& a : argsWithProg) {
        std::cout << a << " ";
    }
    std::cout << std::endl;

    for (const auto& a : argsWithoutProg) {
        std::cout << a << " ";
    }
    std::cout << std::endl;

    std::cout << arg << std::endl;

    return 0;
}

To experiment with command-line arguments, it’s best to compile the program first:

$ g++ -fcilkplus command_line_arguments.cpp -o command_line_arguments
$ ./command_line_arguments a b c d
./command_line_arguments a b c d
a b c d
c

In Cilk, we use the standard C++ way of handling command-line arguments. The main function receives two parameters: argc (argument count) and argv (argument vector). We use these to create vectors of strings for easier manipulation.

Note that Cilk is an extension of C++, so we can use all C++ standard library features. We’ve used std::vector and std::string for more convenient handling of the arguments.

The program demonstrates how to access all arguments (including the program name), how to access arguments without the program name, and how to access a specific argument by index.

Next, we’ll look at more advanced command-line processing with option parsing libraries available in C++.