"0 Basic Learning iOS development" "02-c language" 11-declaration and definition of functions

Source: Internet
Author: User


directory of this document
    • Declaration of a function
    • Ii. development of multi-source files
    • Third, #include


In the previous lecture, the definition and use of functions are briefly introduced, so long as you want to complete a new function, the first thing you should think of is to define a new function to accomplish this function. This will continue to introduce other uses and considerations for the function.


Back to top one, declaration of function 1. In C, the order in which functions are defined is fastidious: By default, only the functions defined later can invoke the previously defined function
1 int sum(int a, int b) {
2     return a + b;
3 }
4 
5 int main()
6 {
7     int c = sum(1, 4);
8     return 0;
9 }


The main function defined by line 5th calls the SUM function of line 1th, which is legal. If you change the order of the SUM function and the main function, it is not legal in the standard C compiler environment (but only a warning in the GCC compiler Environment)





2. If you want to write the definition of a function after the main function, and the main function can call these functions normally, then you must declare the function in front of the main function.
1 // Just make a function declaration, no implementation needed
  2 int sum (int a, int b);
  3
  4 int main ()
  5 {
  6 int c = sum (1, 4);
  7 return 0;
  8 }
  9 
10 // function definition (implementation)
11 int sum (int a, int b) {
12 return a + b;
13}


The SUM function is defined in line 11th, the SUM function is declared on line 2nd, and the SUM function is called normally in line 6th (main function).





3. Declaration Format for Functions


1> format


return value type  function name (parameter 1, parameter 2, ...)


As long as you declare a function before the main function, the main function knows the existence of the function and can call this function. And as long as you know the function name, the return value of the function, how many arguments the function receives, and what type each parameter is, it is possible to call this function, so you can omit the parameter name when declaring the function. For example, the SUM function declaration above can be written like this:


int sum (int, int);


What exactly does this function do, and what is the definition of the function?






2> If there is only a function declaration, and there is no definition of the function, then the program will error when linking



The following syntax is incorrect:


1 int sum(int a, int b);
2 
3 int main()
4 {
5     
6     sum(10, 11);
7 
8     return 0;
9 }
    • A sum function is declared on line 1th, but the SUM function is not defined, and then the SUM function is called on line 6th
    • This program can be compiled successfully, because we declare the SUM function before the main function (the function declaration and definition are different), this function declaration can be understood as: in syntax, cheat the main function, tell it that the SUM function exists, So, from a grammatical point of view, the main function can call the SUM function. Does this sum function exist or is it defined? The compiler is no matter. In the compile phase, the compiler does not detect that the function has no definition, and only when the link is detected does the function exist, that is, the detection function is not defined.
    • Therefore, this program will be in the link when the error message, errors are as follows:




    • My source file here is the main.c file, so a MAIN.O file is generated after the compilation is successful. When linking, the linker detects that the function in the MAIN.O is undefined.
    • The above error message roughly means that the sum identifier could not be found in the MAIN.O file.
    • The linker in the error message is the linker's meaning, and the next time you see this linker, it means that the link phase is wrong. If the link fails, the executable cannot be generated and the program cannot run.
    • The solution to this error is to add the definition of the SUM function.




Back to top ii. development of multi-source files 1. Why you have multiple source files


1> in writing the first C program has been mentioned: we write all the C language code is stored in the extension of the. C source file, after the completion of the compilation, link, and finally run the program.



2> in the previous learning process, because the code is relatively small, so all the code is saved in a. C source file. However, in the actual development process, the project is bigger, the source code is certainly very many, it is easy to tens of thousands of lines of code, even on the 100,000, millions are possible. This time if all the code is written in a. C source file, then this file will be very large, and very disgusting, you can imagine that a file has a hundred thousand of lines of text, do not say debugging programs, even reading code is very difficult.



3> Also, the company is based on team development, if multiple developers at the same time modify a source file, it will bring a lot of trouble, such as Zhang San modified code is likely to erase John Doe previously added code.



4> therefore, for modular development, it is common to write different functions into different. C source files, so that each developer is responsible for modifying the different source files, to achieve the purpose of division of labor, can greatly improve the development efficiency. In other words, a normal C language project is composed of multiple. C source files.





2. Write the sum function to a different source file


The next step is to demonstrate the development of multiple source files, and I write the SUM function previously defined in another source file (named Sum.c). At this time, there are two source files:


1> main.c File
1 int main()
2 {
3 
4     return 0;
5 }
2> sum.c File
1 int main()
2 {
3 
4     return 0;
5 }




3. Call the SUM function in the main function


1> now wants to call the SUM function in the main function, you might write this directly:


1 int main()
2 {
3     int c = sum(10, 11);
4 
5     return 0;
6 }


This type of writing in the standard C language compiler is a direct error, because the main function is not aware of the existence of the SUM function, how can call it!!!



2> we should lie to the main function, the SUM function is present, telling it the return value of the SUM function and the type of the parameter. In other words, the SUM function should be declared before the main function.



The main.c file should be written as follows


1 int main()
2 {
3     int c = sum(10, 11);
4 
5     return 0;
6 }


Notice that line 3rd adds a declaration for the sum function. In order to verify the call result of the SUM function, the result is output in line 9th with the Prinf function.





4. Compile all the source files


Once the SUM.C and MAIN.C have been written, they can be compiled using the GCC directives. The instructions for compiling two files at the same time are:cc-c main.c sum.c



After a successful compilation, 2. O Target files are generated






can also be compiled separately:



Cc-c MAIN.C



Cc-c SUM.C





5. Link to all target files


Previously compiled successfully, MAIN.O and SUM.O files were generated. The 2. o files should now be linked to generate the executable file.



1> Note, be sure to link two files at the same time. If you just link main.o or sum.o alone it is impossible to link successfully. The reasons are as follows:


    • If the only link to the MAIN.O file:cc MAIN.O, the error message is: The sum is not found in the MAIN.O identifier, in fact, the definition of the SUM function is not found. Because the SUM function is defined in the SUM.O file, only the declaration of the sum function in MAIN.O




    • If you are simply linking the SUM.O file:cc SUM.O, the error message is: The main function cannot be found. The entry point of a C program is the main function, the main function is defined in the MAIN.O, the SUM.O does not define the main function, not even the portal, how to link success, build executable file?


It can be seen that MAIN.O and SUM.O have an inseparable relationship, in fact, the purpose of the link is to all the associated target file and C-language function library together to generate the executable file.



2> links main.o and sum.o files:cc MAIN.O SUM.O, generated executables a.out






3> run a.out file:./a.out, the result of the run is output on the screen:


C is 21


Description of the function call succeeded, we have successfully called the SUM function in the SUM.C file in the main function of the main.c file



4> can also draw a conclusion: as long as the declaration of a function, you can call this function, compile can be successful. However, if you want this program to work successfully, you must ensure that you can find the definition of the function when linking.





Back to the top three, #include


After understanding the previous knowledge, you can then understand a long time ago question: Each write in the top of the # # is what to do?


1. #include的作用


Let's take a look at the simplest C program:


1 #include <stdio.h>
2 
3 int main()
4 {
5     printf("Hello, World!\n");
6     return 0;
7 }


The function of this program is to output hello,world! on the screen, and we focus on the first line of code.


    • #include is one of the pre-processing directives for C, so-called preprocessing, which is done before the compilation, and the preprocessing directives are usually preceded by #
    • After the #include instruction follows a file name, the preprocessor discovers the #include instruction, finds the file according to the filename, and includes the contents of the file in the current file. The text in the included file replaces the #include instruction in the source file as if you had copied all the contents of the contained file to the location of the #include instruction. So the first line of instructions is to copy all the contents of the Stdio.h file into the first line.
    • If the included file extension is called. h, we call it "header file", the header file can be used to declare functions, and to use these functions, you must first include the header file where the function is located with the #include directive
    • The #include directive is not limited to. h header files, and can contain any C + + code files that the compiler can recognize, including. C,. HPP,. cpp, and so on, even. txt,. ABC, etc.


In other words, you can put the code of line 3rd ~ line 7th into other files, and then include them with #include instructions, such as:



1> the code from line 3rd to line 7th into My.txt






2> include My.txt file in Main.c source file





    • After the link is compiled, the program can still run as usual, because the #include function is to completely copy the contents of the file to the location where the #include instruction is located
    • Note: Here with TXT file purely demo, usually do projects do not do this, unless eat full of support, will write the code into TXT




2. #include可以使用绝对路径


The above # include "My.txt" uses a relative path, but it can also use an absolute path. Like # # # "/users/apple/desktop/my.txt"





3. The difference between the #include <> and # include ""


The difference between the two is that when the file path of the include is not an absolute path, there are different search orders.



1> for using double quotes "" To include files, search by the following order:


    • Search within the folder of the parent file of this include directive, the so-called parent file, which is the file where the include directive is located
    • If the previous step is not found, the parent file's parent file in the same folder search;
    • If the previous step is not found, search within the include path set by the compiler;
    • If the previous step is not found, search within the system's include environment variable


2> for use of angle brackets <> to include files, search by the following order:


    • Search within the include path set by the compiler;
    • If the previous step is not found, search within the system's include environment variable


I am using the clang compiler, the clang setting include path is (4.2 is the compiler Version):/usr/lib/clang/4.2/include



The Include paths for Mac systems are:


    • /usr/include
    • /usr/local/include




4.stdio.h


We already know the role of the # include directive, but why should we include stdio.h in the first line of code?


    • Stdio.h is a header file in the C language library that declares some common input and output functions, such as the printf function for outputting content to the screen.
    • The reason for the inclusion of the stdio.h file is that the printf function declared inside the stdio.h is used in line 5th, which outputs the data to the screen, and the 7th line of code outputs: Hello, world!
    • Note: There is only a declaration of the printf function in stdio.h. As mentioned earlier: if you know the declaration of a function, you can call this function and it will compile successfully. However, if you want this program to work successfully, you must ensure that you can find the definition of the function when linking. In fact, in addition to the link will be all the target files together, but also associated with the C language function library, the function library has the printf function definition. Therefore, the previous program can be linked successfully.




5. header file. h and source file. C Division of Labor


Like the printf function, we often write the declaration and definition of a function in a different file in development, the function declaration is placed in the. h header file, and the function definition is placed in the. C source file.



Let's put the Declaration and definition of the SUM function in sum.h and SUM.C, respectively.



This is the sum.h file



This is the Sum.c file



Then include sum.h in main.c to use the SUM function






In fact, sum.h and SUM.C filename is not the same, you can write casually, as long as the file name is legitimate. But it is recommended to write the same, because a look at the file name to know that Sum.h and SUM.C are linked.



Run Step Analysis:



1> before compiling, the pre-compiler copies the contents of the sum.h file into the MAIN.C



2> then compiles the main.c and sum.c two source files, generating the target file main.o and SUM.O, the 2 files cannot be executed alone, for simple reasons:



* The main function does not exist in SUM.O and must not be executed



* Although there is a main function in MAIN.O, it calls a SUM function in the main function, and the SUM function is defined in SUM.O, so MAIN.O relies on SUM.O



3> linking MAIN.O and SUM.O to generate executables



4> Running the program





Here, some people may have doubts: Can you include SUM.C files in Main.c, don't sum.h files?





We all know that the feature of # include is to copy content, so the above code is equivalent to:






Such a look, there is absolutely no problem in grammar, MAIN.C, SUM.C can compile successfully, respectively, generate SUM.O, MAIN.O file. But when we link MAIN.O and SUM.O at the same time, errors occur. Cause: When linking these two files, the linker will find that both SUM.O and MAIN.O have the definition of the SUM function, and then report the "duplicate identifier" error, meaning that the SUM function is defined repeatedly. By default, the C language does not allow two functions to have the same name. So don't try to include those. C source files.





Some people may feel that the separation of sum.h and sum.c file of this practice silly B, good 2 more files, you put all the things are written to main.c not be OK?
    • Yes, the code for the entire C program can be written in main.c. However, if the project is done very well, you can imagine how large the main.c file would be and would severely reduce the efficiency of development and commissioning.
    • To do a great project well, you need a team to work with, not one person can make the set. If all the code is written in main.c, it will cause code conflicts, because the entire team of developers are modifying the Main.c file, Zhang San the modified code is likely to erase the code that was added before John Doe.
    • The normal pattern should be this: assuming Zhang San is responsible for writing the main function, John Doe is responsible for writing other custom functions, Zhang San need to use a John Doe write a function, how to do? John Doe can write the declaration of all custom functions in a. h file, such as Lisi.h, and then Zhang San in his own code with # include lisi.h files, then you can invoke the functions declared in lisi.h, and John Doe, you can independently in another file ( For example LISI.C) write the definition of a function to implement those functions declared in lisi.h. In this way, Zhang San and John Doe can work together and do not clash.


"0 Basic Learning iOS development" "02-c language" 11-declaration and definition of functions


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.