C Language Learning 012: code files are divided into multiple files and language learning 012
If you write all the code to a file, it will not be a problem for a small project, but when it is a large project, if you write all the code to a file, it is not only difficult to develop, but also a headache for maintenance. Therefore, we should create corresponding code files based on different functions, in the following example. c code is divided into multiple files
1 #include <stdio.h> 2 3 int main(){ 4 int n=10; 5 int m=5; 6 int result; 7 result=add(n,m); 8 printf("n+m=%i\n",result); 9 result=sub(n,m);10 printf("n-m=%i\n",result);11 return 0;12 }13 14 int add(int n,int m){15 return n+m;16 }17 18 int sub(int n,int m){19 return n-m;20 }
First, we put the function code in another file cal. c.
1 #include "cal.h"2 3 int add(int n,int m){4 return n+m;5 }6 7 int sub(int n,int m){8 return n-m;9 }
Then place the function declaration in the header file cal. h of another file.
int add(int n,int m);int sub(int n,int m);
Now let's look at how to call these methods in the main program.
1 #include <stdio.h> 2 #include "cal.h" 3 4 int main(){ 5 int n=10; 6 int m=5; 7 int result; 8 result=add(n,m); 9 printf("n+m=%i\n",result);10 result=sub(n,m);11 printf("n-m=%i\n",result);12 return 0;13 }
You only need to reference the "cal. h" header file at the beginning of the main program file. Note that the cal. h header file here uses double quotation marks instead of brackets;
The header file referenced by double quotation marks is the relative path of the program, and the header file referenced by Angle brackets is the absolute path of the program.
Finally, let's take a look at how to compile a program with multiple files. In fact, it is no different from compiling a single file, that is, adding c files one by one after gcc.