Chapter 2
This chapter gives an overview of C programs and procedures, and also describes the important terms and characteristics of understanding C procedures and composition components. The subject of discussion includes:
* Source file and source program
* MAIN function and program execution
* Command line parameter analysis
* Survival period, range, visibility and connection
* Name Space
Because this chapter is an overview, the topics discussed only include some introduction materials, and see more information about cross-references.
Source file and source program
A source program can be divided into one or more "source files" or "conversion unit". Enter the compiler is called a "conversion unit".
grammar
Conversion unit:
External description
External Description of Conversion Unit
External description:
Function definition
Description
Chapter 3, "Description and Type", given the syntax explaining the non-terminator, the "preprocessor reference" after this volume explains how to handle the conversion unit.
Note: For the explanation of the ANSI syntax rules, see the introduction of the appendix A "C language syntax summary" behind this volume.
The composition ingredient of a conversion unit is an external description including a function definition and an identifier. These descriptions and definitions can be used in other files required by the source file, header file, library, and the program, you must compile each conversion unit and link the target file generated to generate a program.
A C "source program" is a command, compile indication, description, definition, clause block, and function, in order to make a Microsoft C program take effect, each composition ingredient must have the syntax described in this book, although they can be in any order Place in the program (obey the rules depicting the book). However, these composition ingredients do not affect the variables and functions used in a program (for more information, see "Survival, Scope, Visibility, and Connection" source files behind this chapter do not need to include executable statements For example, you may find this way is useful, place the definition of variables in a source file, and then reference these variables in another source file. This technology is easy to find and modify the definition, the same reason, constants and macros often consist in a separate file called "including files" or "header file", which is required to reference them in the source file, information about macros, including files, See "Preprocessor Reference" behind this volume.
Preprocessor command
A "command" indicates that the C pre-regulator performs a specific action for program text before compiling. The preprocessor command is a sufficient description in the "Pre-Processor Reference" behind this volume, this example uses the preprocessor command #define:
#define max 100
This statement tells the compiler to replace each appearance of MAX before editing. The C compiler preprocessor command is:
#define #ENDIF #ifDef #Line
#elif #Error #ifndef #pragma
#ELSE #if #include #undef
Compile instruction
Microsoft Special Office
A "Compile Indicator" indicates that the compiler performs a special action when compiling. Compiling indicates that changes from the compiler to the compiler. For example, you can use the Optimize to compile indication to set optimizations to be performed by your program. Microsoft C Compile Indicates:
Alloc_text data_seg inline_recursion setlocale
Auto_inline functionintr inSic Warning
Check_stack HDRSTOP MESSAGE
Code_SEG Include_Alias PTIMize
Comment inline_Depth Pack
For a description of the Microsoft C compiler compilation indication, see Chapter 2, "Compile Indication Command" in the "Preprocessor Reference" behind this volume.
Microsoft End
Description and Define a "description" to establish an association between a specific variable, function, or type and its properties. Chapter 3, "Description and Types", gives an ANSI syntax explaining a non-endifier, and an explanation also points to the place and time of an identifier ("connection" of the identifier).
Refer to "Survival, Scope, Visibility, and Connections" behind this chapter. "Definition" of a variable establishes the same association as the description, which also causes the storage of the variable.
For example, main, find and count functions, and var and VAL variables are defined in one source file:
Void main () {} int var = 0; double val [maxval]; char far (fileptr) {} int count (double f) {}
Variables var and values are used in the Find and Count functions, without further description, but their names are invisible (cannot access) in main. Function description and definition
The function prototype establishes the name of the function, its return value, the type and number of its shape. A function definition includes a function body.
Functions and variable descriptions can appear internal or external to a function defined. Any description of a function definition is called "internal" or "local". All functions define the external instructions as "external", "global" or "file range". The variable definitions may be performed in the inner layer (one function definition internal) or an external layer (outside of all functions). The function definition always appears outside. A further discussion of function definitions in Chapter 6, "Function" of "Function". The function prototype is discussed in "Function Prototype" in Chapter 6.
Piece
Description, definition and statement sequences are referred to as a "block". There are two types of blocks C. The composite statement is a statement consisting of one or more statements (see "Composite Scala" in Chapter 5, "Spectrans"), which is a type of block. Another type of block is "function definition", which is incorporated with the "head" associated with this function (the function name, return type, and meticulum). Another block in a block is called "nested".
Note that all composite statements are enclosed in the parentheses, but not anything in the curly brackets makes a compound statement, for example, array, structural or enumerated elements, the specifications of the elements appear in the curne, but they are not Composite statement.
Example program
The following C source program consists of two source files, which give an overview of various possible descriptions and definitions in a C program. The chapters of this book discuss how to write these instructions, definitions, and initialization, and how to use C such as static and extern. The PrintF function is described in the C header file stdio.h.
Main and max functions assume that in separate files, the execution of the program starts from the main function. The user function will not be explicitly executed before main.
/ ************************************************** *********
File1.c-mainfunction
*********************************************************** ******** /
#define one 1 # Define Two 2 # Define Three 3 # include int a = 1; / * Define external variables * / int b = 2; Extern Int Max (int A, int b); / * Function prototype * / INT main () / * MAIN function Definition * / {INT C; / * Definition of two uninited local variables * / int D; Extern Int u; / * Recall other places defined external variables * / static int v; / * Defines variables with continuous survival * / int w = one, x = two, y = three; int z = 0; z = max (x, y); / * Executable statement * / w = max (z, w); Printf ("% D% D / N", Z, W); return 0;}
/ ************************************************** *********
File2.c - defination of max function
*********************************************************** ******** /
Int Max (int A, int b) / * Note form parameters included in the function head * / {IF (a> b) Return (a); else return (b);}
File1.c includes a prototype of the MAX function, which is sometimes referred to as "forward description" because the function is used prior to use. The definition of the main function includes calling MAX. The row started with #define is the pre-regulator command. These commands tell the compiler to replace identifiers One, Two, and Three in File1.c, respectively. The row at the beginning of #include tells the compiler to include file stdio.h, which contains the prototype of the Printf function. The preprocessor command explains in the Pre-Processor Reference behind this volume.
File1.c Use the definition description to initialize global variables A and B, local variables C and D illustrate but not initialized. All of these variables are allocated. Static and external variables U and V are automatically initialized to 0. Therefore, only A, B, U and V are in the description, because they are explicitly or implicitly initialized. F12.c contains the function definition of Max. This definition satisfies Max in File1.c.
The survival and visibility of the identifier are discussed in "Survival, Scope, Visibility, and Connections" behind this chapter. See Chapter 6, "Functions" for more information on functions.
MAIN function and program execution
Each C program has a main (main) function that must be main. If your code service is designed from a single code program, you can use the wide character version of Main. The main function is the starting point of the program execution. The program is typically controlled by calling other functions in the program. A program is executed to Main, but it can terminate in other programs due to various reasons. At this time, you may detect an error, you have to force a program to terminate, for this, use the EXIT function. See the "Microsoft Visual C 6.0 Runtout Reference" volume of the Microsoft Visual C 6.0 Running References for the use of the Exit function. The function in the source program implements one or more specific functions. The main function calls these functions to achieve their respective functions. When MAIN calls another function, it passes the execution control to the function, so it starts from the first statement of the function. When an RETURN statement is executed or reaches the end of the function, the control is returned to main.
You can explain that any function includes the parameters of the main. The term "parameter" or "ginseng" refers to an identifier that accepts a value transmitted to the function. See "Parameters" in Chapter 6, "Parameters" in Chapter 6, for information on transmitting parameters. When a function calls another function, the called function acquires its parameter value from the call function, which is called "parameter". You can explain the methanue for Main so that it accepts parameters from the command line using the following format:
Main (int Argc, char * argv [] * envp [])
When you want to send information to main, parameter habits are named Argc and Argv, although the C compiler does not require these names. Argc and Argv are defined by C language. If you pass it to the third parameter, you are used to name this parameter as ENVP. The examples later in this chapter illustrate how to use these three parameters to access command line parameters. The following section explains these parameters. See the next section "Use WMAIN" for the description of the MAIN wide character version.
Use WMAIN
Microsoft Special Office
In single code program design mode, you can define the wide character version of the main function. If you want to write a portable code from a single code program design mode, use WMAIN instead of Main.
You can use the format similar to Main description of the formal parameters of WMAIN, then transmit a wide character parameter and optional width character environment pointer to the program. WMAIN's Argv and ENVP parameters are Wchar_t * types, for example:
WMAIN (int Argc, wchar_t * argv [], wchar_t * envp [])
If your program uses a main function, build a multi-byte character environment by running in the launcher. When needed (for example, calling _wgetenv or _wputenv functions) only establishes a wide character copy of this environment. If an MBCS environment already exists, the first call _wputenv or the first call _WGetenv, the corresponding wide string environment is established, and then points from the _wenviron global variable to it, the variable is the wide variable of the _Environ global variable. Character version. At this time, two copies of the environment (MBCS, and single code) are present at the same time, and maintenance is performed by the operating system in the program survival.
Similarly, if your program uses a WMAIN function, create a wide character environment when the program starts and points from the _wenviron global variable to it. Create an MBCS (ASCII) environment when calling _putenv or getenv, and pointing it by the _Environ global variable. For more information on the MBCS environment, see the Microsoft Visual C 6.0 Run Reference Volumes of the Microsoft Visual C References. Microsoft End
Parametric description
The Argc parameter of the Main and WMAIN functions is an integer indicating that the number of participants passing the program from the command line. Since the program name is also considered as a parameter, the value of the ARGC is at least 1. The Argv parameter is a pointer array that represents a string end of the program parameter. Each element of the array points to a string passing to Main (or WMAIN) (for information on the array, see "Array Description" in Chapter 3, "Description and Types"). The Argv parameter can be explained as a pointer array of type charity (char * argv []) or pointer (char ** argv) of the type charity pointer. For WMAIN, the Argv parameter can be explained as a pointer array (Wchar_t * argv []) or pointer (wchar_t ** argv) of the pointer of type WCHAR_T. The first string (argv [0]) is the program name, the last pointer (argv [argc]) is NULL (see "Microsoft Visual C 6.0 Run Reference" for obtaining environment variable information " ").
Microsoft Special Office
The ENVP parameter is a pointer to the array of strings ending with space ending in the user environment variable. The ENVP parameter may illustrate a pointer (char ** ENVP) of a pointer array (Char * Envp []) or CHAR ** ENVP. In the WMAIN function, the ENVP parameter can be explained as a pointer (Wchar_T * INVP []) or a pointer of the pointer of Wchar_t (WCHAR_T ** ENVP). The end of the array is directed by null * pointer. Note that the environment block transmitted to Main or WMAIN is a "frozen" copy of the current environment. If you change the environment by calling _putenv or _wputenv, the current environment (returned by GetENV / _WGETENV and _Environ or _wenviron variable) will change, but the block referred to in ENVP does not change. The ENVP parameters are ANSI compatible in C, but is not in C .
Microsoft End Expansion Tongzhuang Parameters
Microsoft Special Office
When running a C program, you can use two wildcard, the question mark (?) And the asterisk (*) indicate the file name and path parameters on the command line.
The command line parameter is handled by a routine called _setargv (called _wsetargv) in a wide character environment, which defaults to the wildcards in the argv string array, which are default. You can use a more powerful version _Setargv to replace normal _setargv by linking to the setargv.obj file link to process wildcards. If your program uses a WMAIN function, link with the WSetargv.obj. For links with setargv.obj or wsetargv.obj, use the / link option, for example:
CL Typeit.c / Link Setargv.obj
This wildcard is expanded in the same manner in the operating system command (if you are not familiar with the wildcard, see your operating system User Guide). A parameter blocking wildcard expansion is blocked in double quotes. In a housitial parameter, you can represent double quotes text by adding a reverse slash (/) before double quotes. If the wildcard parameter does not find a match, the parameter is transmitted as a text.
Microsoft End
Analysis of command line parameters
Microsoft Special Office
When explaining the parameters given by the operating system command line, the Microsoft C started code uses the following rules:
* By blank trimming parameters, it is a space or tabulation.
* A string enclosed by a double quotes as a single parameter, ignoring the blank included in which it contains. A enclosed string can be embedded in a parameter. Note that the insertion mark (^) does not identify as a escape character or delimiter.
* Double quotation number plus a reverse slash (/) is explained as a word double quotes (").
* Reverse slash as text unless they follow one double quotation. * If an even number of reverse slashes follows a double quotation mark, each pair of reverse slash (//) in the Argv array is replaced with a reverse slash, and the double quotes (") is interpreted as a character delimiter. .
* If the odd slash is followed by a double quotation, then each pair of reverse slash (//) in the argv array is replaced by a reverse slash, the double quotes are explained as the remaining reverse slash. The escape sequence causes a text double quotation number (") in Argv.
As explained as described below illustrates the interpretation results of passing several command line parameters of Argv, columns listed in column 2, the results of the third column, and the fourth column come from the output of the ARGS.C program.
Command line output argv [1] argv [2] Argv [3] "ABC" D EA B CDE "AB /" C "" // "DAB" C / DA / / / BD "EF" GH A /// BDEFGHA /// "BC DA /" BCDA "BC" D EA // B CDE
* Array * / char ** envp) / * Environment variable string array * /
{int count; / * Show each command line parameter * / printf ("/ ncommand-line arguments: / n"); for (count = 0; count An output example of this program is as follows: Command-line arguments: argv [0] c: /msc/test.exeenvironment variables: comspec = c: /nt/system32/cmd.exepath=c: / nt; c: / binb; c: / binr; c: / NT; c: / system32; c: / word; c: / help; c: / msc; c: /; prompt = [$ P] temp = c: / tmp = c: / tmp editors = c: / binr WINDIR = C: / NT Microsoft End Custom command line processing If your program does not need command line parameters, you can save some spaces by blocking routines that implement command lines, this routine is called _setargv (in wide character environment for _wsetargv), as in front of this chapter "Expand wildcard The parameters are described. To prevent it from using the routines that do not do anything in a file containing the main function, name _setargv (in the wide character environment is _wsetargv). Then call _setargv or _wsetargv to meet your defined _setargv or _westargv without loading the library version. Similarly, if you don't access the environment table via ENVP parameters, you can provide your own empty routine in the environmental processing routine_setenvp (or _wsetenvp). If your program calls the _SPawn or _exec cluster in the C run, you don't block the environmental processing routine because this routine is used to pass an environment to a new process from the breeding process. Survival, range, visibility and connection To understand how the C program works, you must master the rules that use variables and functions in the program. Several concepts are important to master these rules: * Survival period * Range and visibility *connection Survival "Survival" is a cycle where a variable or function exists during a program execution. It has determined its survival during storage of the identifier. The identifier description with the storage class indicator Static has a static memory period. Identifiers (also known as "global") have stored and determined values during a program. The storage and value are determined only once before the program starts. The identifier described in the external or internal connection has a static memory period (see "Connection" later in this chapter). If the identifier description description description of the Static storage class If it is inside one function, it has an automatic storage period, an identifier having an automatic storage period (a partial identifier) is only in the block of the identifier. Store and determined values, an automatic identifier assigns new storage each time the program enters the block, which will lose its storage (and its value) when the program exits the block. In a function, it also has an automatic storage period in an identifier of non-connection description. The following rules indicate whether an identifier has a global (static) or partial (automatic) survival: * All functions have a static survival. So they exist at any time during the program execution. The identifier illustrated in the external layer (i.e., the function of the function in the program defines the exterior of all blocks of the same level). * If a local variable has an initializer, it initializes it (unless it is static) each time the variable is established. The function parameters also have a local survival. You can specify a global survival for an identifier by including the Static storage class indicator in one block. Once the Static is explained, the variable retains it from an inlet of the block to the value of the next entry. Although the identifier having a global survival is present in the entire execution of the source program (eg, an external description variable or a local variable description with Static keyword), it may be invisible to all parts of the program. See "Range and Visibility" for information on visibility. See Chapter 3, "Storage Class" in Chapter 3, "Description and Types", for the discussion of the storage class indicator. If you need to assign a memory (dynamic), you can implement it using a particular library routine such as Malloc. Since the dynamic memory allocates the library routine, it does not use a part of the language. See the Malloc function in the Microsoft Visual C 6.0 Run Reference. Range and visibility The "visibility" of an identifier determines the program part of the reference, is its "range". A identifier is only visible only in its "range" (that is, can be used), which can be limited to the file, function, block, or function prototype containing its files (in order to increase limit) . The range of an identifier is the program part of its name. Sometimes called "lexical range". There are four types of ranges: functions, files, blocks, and function prototypes. All identifiers except the label are all descriptions to determine its range. The rules of each of the following types determine the visibility of the identifier in a program: File range Description or type indicator with file range appears outside of any block or parameter table, can be accessed anywhere in the conversion unit after the description. The identifier name with file range is often referred to as "global" or "external". The range of a global identifier begins with where its definition or description is terminated, and terminates at the end of the conversion unit. Function range A label is the only identifier with a function range. A label is implicitly illustrated by the statement it uses. In a function, the label name must be unique (more information about the reference numeral and label name, see "GOTO and label statement" in Chapter 5, "Statement"). Block range Description or type indicator with the identifier of the block range appears in a description table of the formal parameters defined within one block or a function. It is visible only in the range of the blocks of the blocks that are described and defined to block the blocks containing their definitions or instructions. It limits the block of the block and the block of the block to close the correlation block. Such an identifier is sometimes referred to as "local variable". Function prototype Description or type indicator with a function prototype range or type indicator appears in a parameter description table in a function prototype (not the description portion of the function). It ranges at the end of this function. The appropriate description of variable visibility in other source files is described in "Storage Class" in Chapter 3, "Description and Type". The variables and functions described in the external layer Static storage class indicator description are only visible in the defined source file, and all other functions are globally visible. Summary of survival and visibility Table 2.1 is a summary of the survival and visibility characteristics of most identifiers. The start three columns give attributes defined the living and visibility, and the survival and visibility of the identifier with the beginning of the three column attributes are given in column 4 and 5. But the table does not include all possible situations. See Chapter 3, "Storage Class" in Chapter 3, "Description and Types". Table 2.1 Summary of survival and visibility Property: Result: Level Item Storage Class Indicator Visibility File range variable Defines the remainder in the STATIC globally. Variable Description EXTERN globally in the remaining part of its source file in its source file, or defines the remainder of a function prototype Static Externate Block range variable Description Externally Global Block Variable definition static global block Variable Definitions of AUTO or REGISTER partial blocks The following example shows the visibility of blocks, nesters, and variables: #include int = 1; / * i Definitions in the external layer * / INT main () / * main defines external layer * / {printf ("% d / n", i); / * Print 1 (value of external layer i) * / {/ * Start the first nested block * / INT i = 2, j = 3; / * i and j define in internal layer * / printf ("% D% D / N", I, j); / * Print 2, 3 * / {/ * start The second nested block * / INT i = 0; / * i redefined * / printf ("% D% D / N", I, j); / * Print 0,3 * /} / * End Two nested block * / printf ("% d / n", i); / * Print 2 (definition of the restoration) * /} / * End the first nested block * / printf ("% D / N ", i); / * Print 1 (Restore Outer Definition) * / Return 0;} In this example, there are four-layer visibility: external layers and three block layers. The values printed on the screen have a comment behind each line. Connect The name of the identifier can refer to different identifiers in different ranges, and an identifier will be described in different ranges or within the same range, and the process can be directed to the same identifier or function by a process called "connection". Connection Determines the part of the identifier that can be referenced (it "visibility"). There are three types of connections: interior, external and unconnected. Internal connection If an object or a file range identifier of a function contains a storage class indicator Static, the identifier has an internal connection. Otherwise, the identifier has an external connection. For the discussion of the storage class identifier, see "Storage" in Chapter 3, "Description and Types". In a conversion unit, each instance of an identifier having an internal connection indicates the same identifier or function. The identifier of the internal connection is unique to a conversion unit. External connection If the STATIC storage class indicator is not used in the first description of the identifier of the file range layer, the object has an external connection. If a function of an identifier of a function is not stored, there is no storage class indicator. Its connection seems to be described using the storage class indicator Externern. If an identifier of an object describes that has a file range and does not store a class indicator, its connection is external. A name having an external connection identifier is a description of the external connection of any other same name represents the same function or data object, which may be in the same conversion unit or in a different conversion unit. If the object or function has a global survival, the object or program is shared by the entire program. Unconnected If the identifier in one block does not include an externary storage class indicator, the identifier is not connected, which is unique to this function. The following identifier is not connected: * A identifier illustrates anything else to make a non-object or function. * A identifier illustrates a function parameter. * The block range identifier of an object does not description with the extern storage class indicator. If an identifier is not connected, multiple descriptions of the same name of the same range (in one instruction or type indicator) generate a symbol redefine error. Name space The compiler establishes a "namespace" for identifying identifiers for a variety of different items. The name in each namespace must be unique to avoid conflicts, but the same identifier can appear in multiple namespaces. This means that you can use the same identifier for two or more different items, provided by different namespaces. The compiler solves the reference based on the syntax context of the identifier in the program. Note: Do not indicate that the namespace of the restricted C represents the C "Name Space" feature. For more information, see Chapter 6, "Name Space" in the "Microsoft Visual C 6.0 Language Reference" behind this volume. The description of the namespace used in C is listed below: Statement mark The named statement label is the statement section. The definition of the statement label is always followed by a colon but not a CASE part. The use of statement labels is always followed by the goto keyword. The name label is not distinguished from other names or other functions. Structure, joint and enumeration logo These markers are part of the structure, joint, and enumeration type identifiers. If there is, it always follows the reserved words Struct, Union or Enum. This logo name must be distinguished from the same visibility structure, an enumeration or joint flag. Structural or union Allocating a member name associated with each structure and a federated type in the namespace, that is, the same identifier can be the composition of the components of different structures or federated members. The definition of composition ingredients always appears in a structure or a federal indicator. The use of components is always following the member selection operators (->, and.). In the structure or joint, a member name must be unique, but in order to distinguish with other names, the name of the same structure and the name of the joint, the name of the structure itself. Ordinary identifier All other names in the namespace include all variables, functions (including form parameters, local variables) and enumeration. The identifier name has nested visibility, so you can redefine them in blocks. Typedef logo The type definition (TypeDef) name cannot be used as an identifier within the same range. For example, because structural flags, structural members and variable names are in three different namespaces, three items in this example are named Student without conflict. The context of each item allows each appearance of Student in the program (information about the structure, see "Structure Description" in Chapter 3, "Description and Types"): Struct student {char strd [20] int class; in; When Student appears after the Struct keyword, the compiler identifies it as a structural flag. This name refers to a structural member when Student occurs after a member selectively operates (-> or.). In other context, Student refers to structural variables. But in order not to cause blur, it is recommended not to overload the sign namespace.