Separate Compilation

박영재·2024년 9월 27일

Modular Programming

1. A function is defined in another file

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;
}

2. A function is declared in the current file and defined in another file

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;
}

3. A function is declared in a header file and defined in a source file

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;
}

Sharing Identifiers

extern: Explicitly reference identifiers declared in another source file

Using 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 files

By 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;
}
profile
People live above layers of abstraction beneath which engineers reside

0개의 댓글