C Multiple Source Files: How to Link Them

In the C programming language, calling between multiple source files is typically done through function declarations and definitions. Specifically, if a function is defined in one source file and another source file wants to call this function, the calling source file needs to include the declaration of the function or its header file. This allows the compiler to recognize the function’s definition and call during compilation.

Here is a simple example:

Source file 1: file1.c

#include <stdio.h>

// 定义一个函数
void printMessage() {
    printf("Hello, World!\n");
}

Original file 2: file2.c

// 包含函数声明
void printMessage();

int main() {
    // 调用函数
    printMessage();
    return 0;
}

In this example, file2.c includes the declaration of the printMessage function, so the compiler knows that the printMessage function exists. When compiling file2.c, the compiler will link to the printMessage function defined in file1.c and successfully compile the entire program.

bannerAds