Lecture 8 Program Structure

Bloggers regularly updated [ security research / Push-free, C / C ++, 5G mobile communications, Linux, living essays ] series of articles, like a friend [ thumbs attention + ] Support about it!


Lecture 8 Program Structure

1. Global Variables

1.1 Global Variables

Global variables: define a variable outside the function ,Overall survival and scope

  • They have nothing to do with any function
  • They can be used in any internal function

Global variables are initialized:

  • Uninitialized global variables get a value of 0 (but not local variables)

    • The pointer value will be NULL
  • Only use the known value of compile-time to initialize global variables

  • Their initialization occurs before the main function

Hide global variables:

  • If there is an internal function variables and global variables of the same name, then the global variables are hidden

common sense:

printf("in %s all=%d\n", _func_, all); //此语句中,_func_表示的是函数的名字,用%s输出

1.2 Static local variables

Static local variables: able to continue to maintain the original value after the end of the function of local variables

  • When a local variable definitions plus staticmodifier becomes static local variable
  • When leaving the function, static local variable will continue to exist and retain their value
  • Static local variable **initialization** only do the first time you enter this function, the function will be entered later whenKeep the value of the last to leave

Static local variables and global variables:

  • Static local variable is actuallySpecial global variables
  • They are located in the same memory area
  • Static local variable hasOverall survival, local scope within the function
    • staticHere means the local scope (locally accessible)

1.3 Postscript

Return function pointer:

  • Returns the local address of a variable is dangerous (becauseAfter the function call, the address may be assigned to other variables)E.g:
#include <stdio.h>

int* f(void);
void g(void);

int main()
{
	int *p = f();
	printf("*p=%d\n", *p);
	g(); 
	printf("*p=%d\n", *p);
	
	return 0;
}

int* f(void)
{
	int i=12;
	return &i;
}

void g(void)
{
	int k=24;
	printf("k=%d\n", k);
}

运行结果:
[Warning] function returns address of local variable
*p=12
k=24
*p=24
  • Returns the global variable or static local variable address is safe
  • Return malloc function in the memory is safe, but likely to cause problems
  • The best practice isIncoming pointer return

tips:

  • Do not use global variables to pass parameters and results between function
  • Try to avoid using global variables
  • Function uses global variables and static local variables are thread-safe

2. preprocessor macros and

Preprocessor directive

  • # The beginning of the preprocessor directive
  • They are not components of the C language, but the C language program without them
  • #define macro is used to define a

2.1 macro definition

#define <名字> <值>

  • Note that there is no semicolon at the end, because the statement is not C
  • The name must be one word, value can be a variety of things
  • Before beginning the C language compiler, compiling preprocessor (CPP) will replace the value of the program name (the full text replacement)
  • gcc, use the -save-temps can save temporary files during compilation

Macros

  • If there are other macro name value in a macro, it will also be replaced
  • If the value of a macro more than one line,In addition to the last lineThe other end of the line will need to add \
  • Appears after the value of the macro comments are not treated as part of the value of the macro

Macro no value

  • #define _DEBUG
  • Such macro is conditional compilation , and other behind preprocessor directive to check whether the macro has been defined a

Predefined macros

  • _LINE_ //当前所在的行号 Integer
  • _FILE_ //文件名 String
  • _DATE_ //编译时的日期 String
  • _TIME_ //编译时的时间 String
  • _STDC_ //如果今前编泽器符合ISO标准,那么该宏的值为1,否则未定义

2.2 macro with arguments

Like macro function

  • #define cube(x) ((x)*(x)*(x))
  • Macros can be parameterized

Error DefinitionsMacros

  • #define RADTODEGZ(X) (x*57.29578)//弧度转换成角度
  • #define RADTODEGZ(X) (x)*57.29578

Macro principle with arguments

  • Everything brackets (To the entire value brackets, each parameter appears to be the place brackets
  • The correct definition#define RADTODEGZ(X) ((x)*57.29578)

You can take a number of parameters

  • #define MIN(a,b) ((a)>(b)?(b):(a))
  • It may be combined (nested) use other macros

Macro with arguments

  • Use the code of large programs is very common
  • It can be very complex, such as "production" (and # ## with the help of two operators) function
  • Western cultural differences (China used less, much more with the West)
  • It will be part of the macro inlinesubstitution function

3. Large Program Structure

3.1 a plurality of source code files

Multiple .c files

  • main () in a long code is divided into several functions for
  • A source code file into several files for too long.
  • Two separate source files forming an executable program is not compiled

project

  • Create a new project in Dev C ++, and then to join in several source code files
  • For the project, after all the source files will compile a project in Dev C ++ are compiled, linked
  • Some IDE (such as Visual Studio) have separate compilation (compile) and build (build) two buttons, the former is a single source file is compiled, which links the entire project is done

Compilation unit

  • A .c file is a compilation unit
  • The compiler compiling each coding unit handles only one

3.2 file

TheFunction prototypePlaced in a header file (ending in .h), the need to call this function in the source code files (.c file) #include the header file, you can let the compiler know the prototype of a function at compile time .

#include

  • #include command is a preprocessor, and macros, prior to processing the compiled
  • It all text files that are inserted into intact in its place
  • So you do not have to be in front #include .c file

"" Or <>

  • #include two forms to indicate the file to insert

    • "" Ask the compiler first looks for the file in the current directory (the directory where the .c file), and if not, to the compiler to find the specified directory
    • <> Allow the compiler to look only in the specified directory
    • Own header file with the "" header files in the standard library use <>
  • The compiler knows where the header file in your standard library

  • Environment variables and compiler command-line parameters can also specify the directory to find header files

#include Mistakes

  • #includeNot used to import library, But to insert text content (intact)
  • stdio.h, only prototype of printf , printf code in another place, a .lib (Windows) or .a (Unix) in
  • Now the C language compiler defaults will introduce all of the standard library
  • #include <stdio.h> just to let the compiler know the prototype printf function, to ensure that you give the parameter values ​​when calling the correct type

Header tips

  • The use and definition of the function of the place should #include the header file
  • The general practice is.h any of the same name has a corresponding .c(Except main.c), all foreignThe prototypes for global variables and public functionsInto them

Function not open to the public

  • In front of adding static function makes it a function can only be used in the compilation unit is located in the
  • In front of the static global variable adding to it a global variable that can only be used in the compilation unit is located in the

3.3 Statement

Declare global variables

  • int i;Definition of variables
  • extern int i;Declaration is variable
  • Defined function is defined, the function prototype is declared
  • Can not be initialized variable declarations

Declarations and definitions

  • Statement is (the compiler) does not generate code for something

    • Function prototype
    • Variable declaration
    • Struct declaration
    • Macro declares
    • Enum declaration
    • Type declaration
    • inline functions
  • Defined (so the compiler) code generation stuff

    • function
    • Global Variables

Header rule

  • Only statements can be placed in a header file (rather than legal rules)
  • Otherwise it will create a project in multiple compilation units where there are duplicate entities
  • Some compilers allow a function of the same name exists several compilation units, or by the presence of this weak emphasis modifier

Repeat statement

  • The same compilation unit, the structure of the same name can not be repeated statement
  • If you have a declaration header file structure,Difficult#Include the header file will not be repeated in a compilation unit in (when the project is very complex, there are more than .c, .h file #include each time)
  • So it is necessary == "standard header file structure" ==
#ifndef _LIST_H_ //条件编译
#define _LIST_H_
//如果没有定义这个宏,就定义这个宏
#include "node.h"

typedef struct _list {
    Node* head;
    Node* tail;
} List;
    
#endif

运用条件编译和宏,保证这个头文件在一个编译单元中只会被#include一次;
#pragma once也能起到相同的作用(如VS中),但是不是所有编译器都支持。
头文件结构”==

```c
#ifndef _LIST_H_ //条件编译
#define _LIST_H_
//如果没有定义这个宏,就定义这个宏
#include "node.h"

typedef struct _list {
    Node* head;
    Node* tail;
} List;
    
#endif

运用条件编译和宏,保证这个头文件在一个编译单元中只会被#include一次;
#pragma once也能起到相同的作用(如VS中),但是不是所有编译器都支持。
Published 62 original articles · won praise 109 · views 20000 +

Guess you like

Origin blog.csdn.net/weixin_43871127/article/details/104472853