GCC has many parameters. For example, to translate hello.cinto hello.exe and add debugging information, use GCC hello. C-g-o hello.exe. Now, analyze the GCC parameters. For this example, the parameters can be divided into three parts: the input file (hello. c), whether it contains debugging information (-G), and the output file (-O hello.exe ). The order of the three parts is irrelevant. For example, it can be ensured that the order following-O indicates the output file.
Getopt is a function used in the C standard library to process command line parameters. Its prototype is declared in the unistd. h file:
Int getopt (INT argc, char * const argv [], const char * optstring );
The most critical parameter here is the optstring string. If I want to make a compiler that only supports the-g-o parameter, I need to set optstring to "go:", that is, put the short-term letters in the string. But don't forget the colon ":" After O. The colon indicates that there is a related parameter after this parameter. In terms of purpose,-O is followed by an output file name. Otherwise, it is meaningless. The alphabetic order in optstring is arbitrary. In this example, it can also be written as "O: G ".
The getopt function processes command line parameters one by one. When getopt returns-1, all parameters marked with short lines have been processed. Therefore, we usually use a loop to call getopt repeatedly and use a switch statement in the loop to process different parameters. Let's take a look at the complete program:
# Include <stdio. h>
# Include <unistd. h>
Struct globalopt_t ...{
Int debug;
Char * output;
Char * input;
};
Struct globalopt_t globalopt =... {0, null, null };
Char * opt_string = "go :";
Int main (INT argc, char ** argv )...{
Int OPT;
While (OPT = getopt (argc, argv, opt_string ))! =-1 )...{
Switch (OPT )...{
Case 'G ':
Globalopt. DEBUG = 1;
Break;
Case 'O ':
Globalopt. Output = optarg;
Break;
}
}
Globalopt. Input = argv [optind];
Printf ("Debug: % d/N", globalopt. Debug );
Printf ("input: % s/n", globalopt. Input );
Printf ("output: % s/n", globalopt. output );
Return 0;
}
Note that globalopt. Output = optarg is used when the-O parameter is processed. Optarg is a global variable introduced by getopt. If an option is followed by a parameter, optarg is the value of this parameter. In this example, optarg is the output file name after-o. Outside the loop, there is a globalopt. Input = argv [optind], which is used to get the input file name. In this example, if the option parameter is not added, it is considered to be an input file (which is also designed by GCC) and cannot be parsed using getopt. Here we use the optind global variable, which indicates the index of the next argv pointer when getopt () is called again. In this example, it points to the location of the input file name parameter.
Compile the program as mygcc.exe and run mygcc-O hello.exe hello. C-G on the command line:
Debug: 1
Input: Hello. c
Output: hello.exe