C Language Learning 012: code files are divided into multiple files and language learning 012

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.