We know that the beginning of contact with C programming, is generally in a. C or. cpp (the following is only said. c) in the file to write code, which must have an entry function,
That is, the main () function, you can write all the program code in the main function, of course, if you want the program more modular, you can also write some of the actions in a function
, the declarations and definitions of these functions are also in the main function.
Think about it, as your code gets bigger and more powerful, and in a. c file, you define a myriad of functions that implement different functions,
And it's all mixed up, do you feel like you're messing with the code you're writing? Here I found a way to make the program more modular,
More organized. The general approach is divided into the following steps:
1. Write the declaration of a functionally similar custom function in a. h file (for example: MATH.H)
2. Write the specific implementations of these functions in the. c File (for example: math.c note to include the header file #include "Math.h")
3. Include the header file (#include "Math.h") in your main program (support. c file format), and you can call these custom functions in the main program.
We now want the C function module, which provides the functions of mathematical calculation (such as addition, subtraction, multiplication, and other computational functions), the Custom function is written in Math.h, the function of the
Implementations are written in math.c, and these functions are called in the main function main.c for testing.
I. Preparation of MATH.H files
1 #ifndef _math_h2 #define_math_h3 4#include <stdio.h>5 6 /*7 declaration of a custom Function8 */9 //PlusTen intADD (intAinchb); One //minus A intSub (intAintb); - //Multiply - intMulti (intAintb); the //except - DoubleDev (intAintb);/ /... - #endif
Ii. Preparation of MATH.C documents
1#include <stdio.h>2#include"Math.h" //you must add!!!3 4 intADD (intAintb)5 {6 returnA +b;7 }8 9 intSub (intAintb)Ten { One returnA-b; A } - - intMulti (intAintb) the { - returnA *b; - } - + DoubleDev (intAintb) - { + if(b==0) A { atprintf"\ n The divisor cannot be 0."); - return 0.0; - } - return(Double) A/b; -}
Third, test: MAIN.C (support. c file format) call the function in the module
1#include <stdio.h>2#include <conio.h>3#include"Math.h" //add a header file for a custom function4 5 voidMain ()6 {7 intA= the, b=Ten;8 9 //calling a custom functionTenprintf"a+b=%d\n", Add (A, b)); Oneprintf"a-b=%d\n", Sub (A, b)); Aprintf"a*b=%d\n", Multi (A, b)); -printf"a/b=%f\n", Dev (A, b)); - the getch (); - return; -}
Note: When adding the main program code in VC6.0, you need to add. c Format (MAIN.C), Add. cpp Format (main.cpp) will error,
Specific reasons still do not know, want to know can tell!
The results of the program run:
Attached: The above content for I from the "C Language science and Art" a Book of learning Summary, for everyone to learn and share.
C Program Reference custom C function module