"C language - an implicit function declaration implicit declaration"

1. The concept of implicit function declarations

  In the C language, you do not have to declare the function before calling. If not specified, then the compiler will automatically follow the rules of an implicit statement, resulting in assembly code to C code that calls the function. Below is an example:

int main(int argc, char** argv)
{
    double x = any_name_function();
    return 0;
}

  Simply compile the above source code, and there is no error , but the link because the stage is named not find any_name_function function body and error .  

[smstong@centos192 test]$ gcc -c main.c
[smstong@centos192 test]$ gcc main.o
main.o: the In main function ` ' : 
. main.c :( text + 0x15 ): undefined any_name_function Reference to` ' ( `any_name_function ' references not defined)
 collect2 to: LD returns 1

  The reason why the compiler does not complain because the C language provides a function not declared automatically using implicit declaration. It becomes equivalent to the following code:

int any_name_function();
int main(int argc, char** argv)
{
    double x = any_name_function();
    return 0;
}

2. The problem caused the program

  Examples given above, and will not cause much impact, because it is easy to find problems during the link stage. However inexplicable run-time error will result in the following example.

#include <stdio.h>
int main(int argc, char** argv)
{
    double x = sqrt(1);
    printf("%lf", x);
    return 0;
}

  gcc compiler and linker

[smstong@centos192 test]$ gcc -c main.c
main.c: the function 'main' in which:
main.c: . 6 : Warning: implicit declaration of built-in functions 'sqrt' incompatible
[smstong@centos192 test]$ gcc main.o

  operation result  

1.000000

  Will give a warning when compiled, suggesting implicitly declared with the built-in function 'sqrt' is not compatible. gcc compiler at compile time can be automatically used in the library header file (BIF) function to find the implicit declaration of the same name, if the two are not found to the same, will be declared prototype built-in function to generate the calling code. This is often the programmer expects idea.
  The above function prototype example implicitly declared as:

int sqrt(int);

  Corresponding to the same name and function prototype is built:

double sqrt(double);

  The final compiler has been compiled in accordance with the built-in function prototypes to achieve the desired effect. However, this behavior is not gcc C language compiler specification, not all compiler implementations have such a function.

 

3. implicitly declared function name just link library exists, and returns an int

  

 

Guess you like

Origin www.cnblogs.com/zhuangquan/p/11757879.html