從另一個 C 檔案呼叫函式

foo.h 中

#ifndef FOO_DOT_H    /* This is an "include guard" */
#define FOO_DOT_H    /* prevents the file from being included twice. */
                     /* Including a header file twice causes all kinds */
                     /* of interesting problems.*/

/**
 * This is a function declaration.
 * It tells the compiler that the function exists somewhere.
 */
void foo(int id, char *name);

#endif /* FOO_DOT_H */

foo.c

#include "foo.h"    /* Always include the header file that declares something
                     * in the C file that defines it. This makes sure that the
                     * declaration and definition are always in-sync.  Put this
                     * header first in foo.c to ensure the header is self-contained.
                     */
#include <stdio.h>
                       
/**
 * This is the function definition.
 * It is the actual body of the function which was declared elsewhere.
 */
void foo(int id, char *name)
{
    fprintf(stderr, "foo(%d, \"%s\");\n", id, name);
    /* This will print how foo was called to stderr - standard error.
     * e.g., foo(42, "Hi!") will print `foo(42, "Hi!")`
     */
}

main.c 中

#include "foo.h"

int main(void)
{
    foo(42, "bar");
    return 0;
}

編譯和連結

首先,我們將 foo.cmain.c 編譯目標檔案。這裡我們使用 gcc 編譯器,你的編譯器可能有不同的名稱,需要其他選項。

$ gcc -Wall -c foo.c
$ gcc -Wall -c main.c

現在我們將它們連結在一起以生成我們的最終可執

$ gcc -o testprogram foo.o main.o