The function add is not declared at compile time (this results in a warning), but its definition is found at link time.
// main.c
int main()
{
int result = add(3, 4); // Warning: implicit declaration of 'add'
printf("%d\n", result);
return 0;
}
// add.c
int add(int a, int b)
{
return a + b;
}
In this case, there are no warnings or errors, but the function signature must be declared before use.
The main.c file is somewhat dependent on add.c.
// main.c
int add(int, int); // Function declaration (prototype)
int main()
{
int result = add(3, 4);
printf("%d\n", result);
return 0;
}
// add.c
int add(int a, int b)
{
return a + b;
}
This method is commonly used in modular programming, allowing multiple source files to include the same function declaration via the header file.
// main.c
#include "add.h" // Function declaration via header fileint main()
{
int result = add(3, 4);
printf("%d\n", result);
return 0;
}
// add.h
int add(int, int); // Declaration of 'add'
// add.c
int add(int a, int b)
{
return a + b;
}
extern: Explicitly reference identifiers declared in another source fileUsing extern, global variables declared in one file can be shared with other source files.
// main.c
extern int result; // Use 'extern' to reference a global variable from another file
int main()
{
result = add(3, 4); // Uses global 'result' declared elsewhere
printf("%d\n", result);
return 0;
}
// add.c
int result = 7; // Global variable defined here
int add(int a, int b)
{
result = a + b; // Updates global 'result'
return result;
}
static: Hide global identifiers from other source filesBy using static, global variables are limited to the current source file, preventing access from other files.
// main.c
static int result = 7; // Global variable restricted to 'main.c'
int main()
{
result = add(3, 4); // Uses local 'result'
printf("%d\n", result);
return 0;
}
// add.c
extern int result; // Attempt to use 'result' from 'main.c' causes link error (not found)
int add(int a, int b)
{
result = a + b; // Link error: 'result' is not found
return result;
}