ProgrammingC/Embedded Developer

Explain the difference between declaration and definition of functions and variables in C. What happens if these rules are violated in a multi-module project?

Pass interviews with Hintsage AI assistant

Answer

In the C language, a distinction is made between declaration (declaration) and definition (definition).

  • Declaration informs the compiler of the existence of a function or variable and its type, but does not allocate memory.
  • Definition specifies the actual object or body of the function, effectively reserving memory for the variable or placing the function code.

Examples:

// Declaration (extern) extern int global_var; int func(int); // Definition int global_var = 42; int func(int x) { return x * 2; }

In a multi-module project, declarations are placed in header files so that modules "know about each other," while definitions are placed in only one source file to avoid conflicts during linking.

Trick Question

Can there be multiple identical definitions of the same variable (e.g., int flag = 0;) in different source files if they include the same header file?

Answer: No! The header file should only contain the declaration extern int flag;, and the definition of the variable should be in only one source file (int flag = 0;). Non-compliance will lead to a linking error about multiple definitions.

Examples of real errors due to ignorance of the topic nuances


Story

In a large project, global variables were "split" in header files as int counter = 0;. This header was included, causing duplication of definitions. The result: a linker error during CI/CD build — “multiple definition of counter.”


Story

In a library of functions, function prototypes were made without type specification, which the compiler flagged as deprecated declaration, then resulted in an error due to function signature mismatches between modules.


Story

During the testing phase, it became clear that some variables were not initialized, as they were declared only as extern, but there was no initialization in any of the modules. This led to garbage reading and elusive bugs on the embedded platform.