You know the arguments to main() that I’ve been carefully avoiding discussing?
int main (int argc, const char * argv[]) { ...
Now you are ready to learn about them. argv is an array of C strings. argc tells you how many strings are in the array. What do these string represent? Command-line arguments.
The command-line tools that you’ve been creating can be run from Terminal. The Terminal app is just a pretty interface to what is called a shell. There are a few different shells with catchy names like csh, sh, zsh, and ksh, but nearly all Mac users use bash. When you run a program from bash, after you type in the program name, you can supply any number of arguments separated by whitespace. Those arguments are packed into argv before main() is called.
Truthfully, Cocoa and iOS programmers seldom use argv and argc. However, if you ever write a handy command-line tool, you will almost certainly need to know how to utilize them.
In Xcode, create a new C Command Line Tool project called Affirmation. Affirmation will take two arguments, a person’s name and a number n. When you run it, that person will be declared cool n times.
$ Affirmation Mikey 3
Mikey is cool.
Mikey is cool.
Mikey is cool.
Before we do that, change main() to just print out each of the arguments in argv:
#include <stdio.h> int main (int argc, const char * argv[]) { for (int i = 0; i < argc; i++) { printf("arg %d = %sn", i, argv[i]); } return 0; }
If you are running this from bash, you could just type in the arguments on the command line.
$ Affirmation Aaron 4
However, to run a program with arguments in Xcode, you must first edit the scheme. Under the Product menu, choose Edit Scheme.... When the sheet appears, select Run Affirmation in the table view on the left. Then select the Arguments tab from the choices at the top of the sheet. Find the list entitled Arguments Passed On Launch and use the + button to add two items: a name and a number.
Click OK to dismiss the sheet.
When you run the program, you’ll get a list of the strings in argv. The one that surprises most people is argv[0]:
arg 0 = /Users/aaron/Library/Developer/Xcode/DerivedData/ Affirmation-enkfqsgavfsproeggoxwbrmcowvn/Build/Products/Debug/Affirmation arg 1 = Aaron arg 2 = 4
argv[0] is the path to the executable file.
If your program takes arguments, the first thing you should do is make sure that the number of arguments is correct. Edit main.m:
#include <stdio.h> #include <stdio.h> // atoi() int main (int argc, const char * argv[]) { if (argc != 3) { fprintf(stderr, "Usage: Affirmation <name> <number>n"); return 1; } int count = atoi(argv[2]); for (int j = 0; j < count; j++) { printf("%s is cool.n", argv[1]); } return 0; }
atoi() is a standard C function that reads a C string and tries to make an int out of it.