The function is visible even if it is not included in C

I have defined a function A

in a main.c

file. I have created three libraries that use a function A

without importing anything. The code works, but I have only one warning: implicit declaration of function 'A' [-Wimplicit-function-declaration]

.

How is it possible that a function A

works in a function B

defined in a separate file without importing it? How is it possible that I only have one warning when the function A

is called by other functions besides the function B

?

+3


source to share


3 answers


As C

we are not "import" function. We will compile the individual translation units into object files and then concatenate them all together to form a binary / executable file.

In the linking phase, the linker checks the object files for the required symbols and links and links them together to create a single executable file (so a function call is possible at runtime).

In your case, the compiler does not "see" the function declaration at call time (so it has no idea about the function signature, which could be a potential error, so you have a "warning"), but at the linking stage, the linker can find a reference to the function (assuming that both translation blocks are linked together to form a binary file) and creates a binary file.



FWIW, implicit function declarations are non-standard according to the latest C standards. You must forward the function declaration (provide a prototype) before you can actually use this function. Quoting C11

, Foreword,

Major changes in the second edition included:

[....]

- remove implicit function declaration

+2


source


Global non-static symbols (variables and functions) have external linkage by default , that is, they can be accessed from other translation units .



+5


source


Compilation:

  • At compile time, each file is compiled separately and finally the .o file is generated from the .c file.

  • For every function called in the file compiler, a function definition or at least a function declaration is expected.

  • In the absence of a definition or declaration, you receive a warning from the compiler, for example, an implicit declaration of function "A"
    [-Wimplicit-function-declaration].

  • In your case, when the function definition is in another file, you should at least include the function declaration in your include file.

Linking:

  • Linking refers to the creation of a single executable file from
    multiple object files. At this point, the commonly used linker will complain about undefined functions.

  • Since function A in main.c is defined globally, it will be used by the library.

+1


source







All Articles